Skip to main content
Module

x/polkadot/util/hex/fixLength.ts

Package publishing for deno.land/x/polkadot
Go to Latest
File

import type { HexString } from '../types.ts';
import { hexAddPrefix } from './addPrefix.ts';import { hexStripPrefix } from './stripPrefix.ts';
/** * @name hexFixLength * @summary Shifts a hex string to a specific bitLength * @description * Returns a `0x` prefixed string with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length. Input values with less bits are returned as-is by default. When `withPadding` is set, shorter values are padded with `0`. * @example * <BR> * * ```javascript * import { hexFixLength } from 'https://deno.land/x/polkadot@0.2.40/util/mod.ts'; * * console.log('fixed', hexFixLength('0x12', 16)); // => 0x12 * console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012 * console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12 * ``` */export function hexFixLength (value: string, bitLength = -1, withPadding = false): HexString { const strLength = Math.ceil(bitLength / 4); const hexLength = strLength + 2;
return hexAddPrefix( (bitLength === -1 || value.length === hexLength || (!withPadding && value.length < hexLength)) ? hexStripPrefix(value) : (value.length > hexLength) ? hexStripPrefix(value).slice(-1 * strLength) : `${'0'.repeat(strLength)}${hexStripPrefix(value)}`.slice(-1 * strLength) );}