mirror of
https://github.com/pezkuwichain/pezkuwi-common.git
synced 2026-04-23 06:08:02 +00:00
31 lines
1.5 KiB
JavaScript
31 lines
1.5 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.hexFixLength = hexFixLength;
|
|
const addPrefix_js_1 = require("./addPrefix.js");
|
|
const stripPrefix_js_1 = require("./stripPrefix.js");
|
|
/**
|
|
* @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 '@pezkuwi/util';
|
|
*
|
|
* console.log('fixed', hexFixLength('0x12', 16)); // => 0x12
|
|
* console.log('fixed', hexFixLength('0x12', 16, true)); // => 0x0012
|
|
* console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12
|
|
* ```
|
|
*/
|
|
function hexFixLength(value, bitLength = -1, withPadding = false) {
|
|
const strLength = Math.ceil(bitLength / 4);
|
|
const hexLength = strLength + 2;
|
|
return (0, addPrefix_js_1.hexAddPrefix)((bitLength === -1 || value.length === hexLength || (!withPadding && value.length < hexLength))
|
|
? (0, stripPrefix_js_1.hexStripPrefix)(value)
|
|
: (value.length > hexLength)
|
|
? (0, stripPrefix_js_1.hexStripPrefix)(value).slice(-1 * strLength)
|
|
: `${'0'.repeat(strLength)}${(0, stripPrefix_js_1.hexStripPrefix)(value)}`.slice(-1 * strLength));
|
|
}
|