UNPKG

1.55 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.hexFixLength = void 0;
4const addPrefix_js_1 = require("./addPrefix.js");
5const stripPrefix_js_1 = require("./stripPrefix.js");
6/**
7 * @name hexFixLength
8 * @summary Shifts a hex string to a specific bitLength
9 * @description
10 * 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`.
11 * @example
12 * <BR>
13 *
14 * ```javascript
15 * import { hexFixLength } from '@polkadot/util';
16 *
17 * console.log('fixed', hexFixLength('0x12', 16)); // => 0x12
18 * console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012
19 * console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12
20 * ```
21 */
22function hexFixLength(value, bitLength = -1, withPadding = false) {
23 const strLength = Math.ceil(bitLength / 4);
24 const hexLength = strLength + 2;
25 return (0, addPrefix_js_1.hexAddPrefix)((bitLength === -1 || value.length === hexLength || (!withPadding && value.length < hexLength))
26 ? (0, stripPrefix_js_1.hexStripPrefix)(value)
27 : (value.length > hexLength)
28 ? (0, stripPrefix_js_1.hexStripPrefix)(value).slice(-1 * strLength)
29 : `${'0'.repeat(strLength)}${(0, stripPrefix_js_1.hexStripPrefix)(value)}`.slice(-1 * strLength));
30}
31exports.hexFixLength = hexFixLength;