utils.js
1 /** 2 * Limits the length of a string for display purposes, replacing the removed text 3 * with the replacement entity specified 4 * 5 * @param {String} strToShorten - string to shorten. 6 * @param {Number} maxLength - maximum length of string before appending the replacement entity. 7 * @param {String} replacement - string to replace the removed text with, defaults to '…' 8 * @param {Boolean} trimMiddle - if true, maxLength chars form the beginning and end will be 9 * shown, and the middle of the string will be trimmed, ie '123…789' (maxLength = 3, delimiter = '…') 10 * @example 11 * const fullLength = '1234567890'; 12 * limitLength(fullLength, 3); 13 * // returns '123…' 14 * @example 15 * const fullLength = '1234567890'; 16 * limitLength(fullLength, 3, '-', true); 17 * // returns '123-890' 18 * @returns {String} the shortened string 19 */ 20 export function limitLength (strToShorten, maxLength, replacement, trimMiddle){ 21 if(!strToShorten) return ''; 22 23 const fullStringLength = strToShorten.length; 24 const ellips = replacement || '…'; 25 26 if(trimMiddle && fullStringLength > maxLength * 2){ 27 return [strToShorten.substring(0, maxLength), ellips, strToShorten.substring(fullStringLength - maxLength)].join(''); 28 } 29 30 if(fullStringLength > maxLength){ 31 return strToShorten.substring(0, maxLength) + ellips; 32 } 33 return strToShorten; 34 } 35 36 /** 37 * Limits the length of an address for display purposes, replacing the removed hex 38 * chars with the replacement entity specified 39 * 40 * @param {String} address - address to shorten. 41 * @param {Number} maxLength - maximum hex chars to show before appending the replacement. 42 * @param {String} replacement - string to replace the removed hex chars with, defaults to '…' 43 * @example 44 * const fullLength = '0x3901F05c5e296E97c8Dc2ebEdCCa5F010f895552'; 45 * limitAddressLength(fullLength, 4); 46 * // returns '0x3901…5552' 47 * @example 48 * const fullLength = '0x3901F05c5e296E97c8Dc2ebEdCCa5F010f895552'; 49 * limitAddressLength(fullLength, 3, '-'); 50 * // returns '0x390-552' 51 * @returns {String} the shortened string 52 */ 53 export function limitAddressLength (address, maxLength, replacement){ 54 if(!address) return ''; 55 let prepend0x = false; 56 57 if(address.startsWith('0x')){ 58 address = address.substring(2); 59 prepend0x = true; 60 } 61 62 return `${prepend0x ? '0x': ''}${limitLength(address, maxLength, replacement, true)}`; 63 } 64 65 /** 66 * Formats an ethereum amount using fixed-point notation. 67 * 68 * @param {any} eth - amount of ethereum to display. 69 * @param {Number} decimals - number of decimal places to display. 70 * @example 71 * const eth = 123.12345678901234567890; 72 * limitAddressLength(eth, 4); 73 * // returns 123.1234 74 * @returns {Number} the ethereum amount in fixed-point notation 75 */ 76 export function formatEth(eth, decimals){ 77 return Number.parseFloat(eth).toFixed(decimals); 78 }