@yoroi/common
Version:
The Common package of Yoroi SDK
52 lines (43 loc) • 1.43 kB
text/typescript
import {isArrayOfType, isString} from './parsers'
/**
* Returns a string representation of the given value, if possible.
* @param {string | string[] | undefined | null} value - The value to convert to a string.
* @returns {string} A string representation of the value, or undefined if not possible.
*/
export function asConcatenedString(
value: string | string[] | undefined | null,
): string | undefined {
if (value === null || value === undefined) return
if (isString(value)) return value as string
if (isArrayOfType(value, isString)) return (value as string[]).join('')
return // TS
}
export function truncateString({
value,
maxLength,
separator = '...',
}: {
value: string
maxLength: number
separator?: string
}): string {
if (value.length <= maxLength) return value
const partLength = Math.floor((maxLength - separator.length) / 2)
const start = value.substring(0, partLength)
const end = value.substring(value.length - partLength)
return `${start}${separator}${end}`
}
export function hexToAscii(hex: string): string {
if (hex === '' || !/^[0-9a-fA-F]*$/.test(hex) || hex.length % 2 !== 0) {
return ''
}
return hex
.match(/.{1,2}/g)!
.map((byte) => String.fromCharCode(parseInt(byte, 16)))
.join('')
}
export function asciiToHex(str: string): string {
return Array.from(str)
.map((char) => char.charCodeAt(0).toString(16).padStart(2, '0'))
.join('')
}