UNPKG

1.69 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.hexFixLength = hexFixLength;
7
8var _addPrefix = require("./addPrefix");
9
10var _stripPrefix = require("./stripPrefix");
11
12// Copyright 2017-2022 @polkadot/util authors & contributors
13// SPDX-License-Identifier: Apache-2.0
14
15/**
16 * @name hexFixLength
17 * @summary Shifts a hex string to a specific bitLength
18 * @description
19 * 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`.
20 * @example
21 * <BR>
22 *
23 * ```javascript
24 * import { hexFixLength } from '@polkadot/util';
25 *
26 * console.log('fixed', hexFixLength('0x12', 16)); // => 0x12
27 * console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012
28 * console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12
29 * ```
30 */
31function hexFixLength(value) {
32 let bitLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;
33 let withPadding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
34 const strLength = Math.ceil(bitLength / 4);
35 const hexLength = strLength + 2;
36 return (0, _addPrefix.hexAddPrefix)(bitLength === -1 || value.length === hexLength || !withPadding && value.length < hexLength ? (0, _stripPrefix.hexStripPrefix)(value) : value.length > hexLength ? (0, _stripPrefix.hexStripPrefix)(value).slice(-1 * strLength) : `${'0'.repeat(strLength)}${(0, _stripPrefix.hexStripPrefix)(value)}`.slice(-1 * strLength));
37}
\No newline at end of file