UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

72 lines (71 loc) 2.5 kB
import { isNonEmptyString } from '../guards/primitives.js'; import { isBase64, isBinaryString, isHexString } from '../guards/specials.js'; import { _padStartWith0, _splitByCharLength } from './helpers.js'; import { base64ToBytes, bytesToBase64, bytesToUtf8, hexToBytes, utf8ToBytes } from './utils.js'; export class TextCodec { constructor() { } static isValidHex(hex) { return isHexString(hex); } static isValidBinary(binary) { return isBinaryString(binary); } static isValidBase64(b64) { return isBase64(b64); } static utf8ToHex(text, spaced = true) { return [...utf8ToBytes(text)] .map((b) => _padStartWith0(b, 'hex')) .join(spaced ? ' ' : ''); } static utf8ToBinary(text, spaced = true) { return [...utf8ToBytes(text)] .map((b) => _padStartWith0(b, 'binary')) .join(spaced ? ' ' : ''); } static hexToUtf8(hex) { return bytesToUtf8(hexToBytes(hex)); } static binaryToUtf8(binary) { if (!isBinaryString(binary)) return ''; const bytes = _splitByCharLength(binary, 8).map((b) => parseInt(b, 2)); return bytesToUtf8(new Uint8Array(bytes)); } static hexToBinary(hex, spaced = true) { if (!isHexString(hex)) return ''; return _splitByCharLength(hex, 2) .map((h) => _padStartWith0(parseInt(h, 16), 'binary')) .join(spaced ? ' ' : ''); } static binaryToHex(binary, spaced = true) { if (!isBinaryString(binary)) return ''; return _splitByCharLength(binary, 8) .map((b) => _padStartWith0(parseInt(b, 2), 'hex')) .join(spaced ? ' ' : ''); } static base64ToUtf8(b64) { if (!isBase64(b64)) return ''; return bytesToUtf8(base64ToBytes(b64)); } static utf8ToBase64(text) { if (!isNonEmptyString(text)) return ''; return bytesToBase64(utf8ToBytes(text)); } static base64ToHex(b64, spaced = true) { return TextCodec.utf8ToHex(TextCodec.base64ToUtf8(b64), spaced); } static base64ToBinary(b64, spaced = true) { return TextCodec.utf8ToBinary(TextCodec.base64ToUtf8(b64), spaced); } static hexToBase64(hex) { return TextCodec.utf8ToBase64(TextCodec.hexToUtf8(hex)); } static binaryToBase64(binary) { return TextCodec.utf8ToBase64(TextCodec.binaryToUtf8(binary)); } }