chore: update to version 14.0.11 and align website URLs

This commit is contained in:
2026-01-11 11:34:13 +03:00
parent ef74383349
commit 19c8d69bd8
1499 changed files with 53633 additions and 89 deletions
+15
View File
@@ -0,0 +1,15 @@
/**
* @name arrayChunk
* @summary Split T[] into T[][] based on the defind size
* @description
* Returns a set ao arrays based on the chunksize
* @example
* <BR>
*
* ```javascript
* import { arrayChunk } from '@pezkuwi/util';
*
* arrayChunk([1, 2, 3, 4, 5]); // [[1, 2], [3, 4], [5]]
* ```
*/
export declare function arrayChunk<T>(array: T[], chunkSize: number): T[][];
+30
View File
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayChunk = arrayChunk;
/**
* @name arrayChunk
* @summary Split T[] into T[][] based on the defind size
* @description
* Returns a set ao arrays based on the chunksize
* @example
* <BR>
*
* ```javascript
* import { arrayChunk } from '@pezkuwi/util';
*
* arrayChunk([1, 2, 3, 4, 5]); // [[1, 2], [3, 4], [5]]
* ```
*/
function arrayChunk(array, chunkSize) {
const outputSize = Math.ceil(array.length / chunkSize);
// shortcut for the single-split case
if (outputSize === 1) {
return [array];
}
const output = Array(outputSize);
for (let i = 0; i < outputSize; i++) {
const offset = i * chunkSize;
output[i] = array.slice(offset, offset + chunkSize);
}
return output;
}
+16
View File
@@ -0,0 +1,16 @@
/**
* @name arrayFilter
* @summary Filters undefined and (optionally) null values from an array
* @description
* Returns a new array with all `undefined` values removed. Optionally, when `allowNulls = false`, it removes the `null` values as well
* @example
* <BR>
*
* ```javascript
* import { arrayFilter } from '@pezkuwi/util';
*
* arrayFilter([0, void 0, true, null, false, '']); // [0, true, null, false, '']
* arrayFilter([0, void 0, true, null, false, ''], false); // [0, true, false, '']
* ```
*/
export declare function arrayFilter<T = unknown>(array: readonly (T | null | undefined)[], allowNulls?: boolean): T[];
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayFilter = arrayFilter;
/**
* @name arrayFilter
* @summary Filters undefined and (optionally) null values from an array
* @description
* Returns a new array with all `undefined` values removed. Optionally, when `allowNulls = false`, it removes the `null` values as well
* @example
* <BR>
*
* ```javascript
* import { arrayFilter } from '@pezkuwi/util';
*
* arrayFilter([0, void 0, true, null, false, '']); // [0, true, null, false, '']
* arrayFilter([0, void 0, true, null, false, ''], false); // [0, true, false, '']
* ```
*/
function arrayFilter(array, allowNulls = true) {
return array.filter((v) => v !== undefined &&
(allowNulls || v !== null));
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @name arrayFlatten
* @summary Merge T[][] into T[]
* @description
* Returns a new array with all arrays merged into one
* @example
* <BR>
*
* ```javascript
* import { arrayFlatten } from '@pezkuwi/util';
*
* arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]
* ```
*/
export declare function arrayFlatten<T>(arrays: readonly T[][]): T[];
+42
View File
@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayFlatten = arrayFlatten;
/**
* @name arrayFlatten
* @summary Merge T[][] into T[]
* @description
* Returns a new array with all arrays merged into one
* @example
* <BR>
*
* ```javascript
* import { arrayFlatten } from '@pezkuwi/util';
*
* arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]
* ```
*/
function arrayFlatten(arrays) {
const num = arrays.length;
// shortcuts for the empty & single-entry case
if (num === 0) {
return [];
}
else if (num === 1) {
return arrays[0];
}
// pre-allocate based on the combined size
let size = 0;
for (let i = 0; i < num; i++) {
size += arrays[i].length;
}
const output = new Array(size);
let i = -1;
for (let j = 0; j < num; j++) {
const a = arrays[j];
// instead of pushing, we just set the entries
for (let e = 0, count = a.length; e < count; e++) {
output[++i] = a[e];
}
}
return output;
}
+10
View File
@@ -0,0 +1,10 @@
/**
* @summary Utility methods that operates on arrays
*/
export { arrayChunk } from './chunk.js';
export { arrayFilter } from './filter.js';
export { arrayFlatten } from './flatten.js';
export { arrayRange } from './range.js';
export { arrayShuffle } from './shuffle.js';
export { arrayUnzip } from './unzip.js';
export { arrayZip } from './zip.js';
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayZip = exports.arrayUnzip = exports.arrayShuffle = exports.arrayRange = exports.arrayFlatten = exports.arrayFilter = exports.arrayChunk = void 0;
/**
* @summary Utility methods that operates on arrays
*/
var chunk_js_1 = require("./chunk.js");
Object.defineProperty(exports, "arrayChunk", { enumerable: true, get: function () { return chunk_js_1.arrayChunk; } });
var filter_js_1 = require("./filter.js");
Object.defineProperty(exports, "arrayFilter", { enumerable: true, get: function () { return filter_js_1.arrayFilter; } });
var flatten_js_1 = require("./flatten.js");
Object.defineProperty(exports, "arrayFlatten", { enumerable: true, get: function () { return flatten_js_1.arrayFlatten; } });
var range_js_1 = require("./range.js");
Object.defineProperty(exports, "arrayRange", { enumerable: true, get: function () { return range_js_1.arrayRange; } });
var shuffle_js_1 = require("./shuffle.js");
Object.defineProperty(exports, "arrayShuffle", { enumerable: true, get: function () { return shuffle_js_1.arrayShuffle; } });
var unzip_js_1 = require("./unzip.js");
Object.defineProperty(exports, "arrayUnzip", { enumerable: true, get: function () { return unzip_js_1.arrayUnzip; } });
var zip_js_1 = require("./zip.js");
Object.defineProperty(exports, "arrayZip", { enumerable: true, get: function () { return zip_js_1.arrayZip; } });
+16
View File
@@ -0,0 +1,16 @@
/**
* @name arrayRange
* @summary Returns a range of numbers ith the size and the specified offset
* @description
* Returns a new array of numbers with the specific size. Optionally, when `startAt`, is provided, it generates the range to start at a specific value.
* @example
* <BR>
*
* ```javascript
* import { arrayRange } from '@pezkuwi/util';
*
* arrayRange(5); // [0, 1, 2, 3, 4]
* arrayRange(3, 5); // [5, 6, 7]
* ```
*/
export declare function arrayRange(size: number, startAt?: number): number[];
+28
View File
@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayRange = arrayRange;
/**
* @name arrayRange
* @summary Returns a range of numbers ith the size and the specified offset
* @description
* Returns a new array of numbers with the specific size. Optionally, when `startAt`, is provided, it generates the range to start at a specific value.
* @example
* <BR>
*
* ```javascript
* import { arrayRange } from '@pezkuwi/util';
*
* arrayRange(5); // [0, 1, 2, 3, 4]
* arrayRange(3, 5); // [5, 6, 7]
* ```
*/
function arrayRange(size, startAt = 0) {
if (size <= 0) {
throw new Error('Expected non-zero, positive number as a range size');
}
const result = new Array(size);
for (let i = 0; i < size; i++) {
result[i] = i + startAt;
}
return result;
}
+5
View File
@@ -0,0 +1,5 @@
/**
* @name arrayShuffle
* @description Shuffles the input array (unlike sort, this is not done in-place)
*/
export declare function arrayShuffle<T>(input: readonly T[]): T[];
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayShuffle = arrayShuffle;
/**
* @name arrayShuffle
* @description Shuffles the input array (unlike sort, this is not done in-place)
*/
function arrayShuffle(input) {
const result = input.slice();
let curr = result.length;
// noop for the single entry
if (curr === 1) {
return result;
}
while (curr !== 0) {
// ~~ is more performant than Math.floor
const rand = ~~(Math.random() * curr);
curr--;
[result[curr], result[rand]] = [result[rand], result[curr]];
}
return result;
}
+5
View File
@@ -0,0 +1,5 @@
/**
* @name arrayUnzip
* @description Splits a single [K, V][] into [K[], V[]]
*/
export declare function arrayUnzip<K, V>(entries: readonly [K, V][]): [K[], V[]];
+16
View File
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayUnzip = arrayUnzip;
/**
* @name arrayUnzip
* @description Splits a single [K, V][] into [K[], V[]]
*/
function arrayUnzip(entries) {
const count = entries.length;
const keys = new Array(count);
const values = new Array(count);
for (let i = 0; i < count; i++) {
[keys[i], values[i]] = entries[i];
}
return [keys, values];
}
+5
View File
@@ -0,0 +1,5 @@
/**
* @name arrayZip
* @description Combines 2 distinct key/value arrays into a single [K, V] array
*/
export declare function arrayZip<K, V>(keys: readonly K[], values: readonly V[]): [K, V][];
+15
View File
@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayZip = arrayZip;
/**
* @name arrayZip
* @description Combines 2 distinct key/value arrays into a single [K, V] array
*/
function arrayZip(keys, values) {
const count = keys.length;
const result = new Array(count);
for (let i = 0; i < count; i++) {
result[i] = [keys[i], values[i]];
}
return result;
}
+29
View File
@@ -0,0 +1,29 @@
type MessageFn = () => string;
/**
* @name assert
* @summary Checks for a valid test, if not Error is thrown.
* @description
* Checks that `test` is a truthy value. If value is falsy (`null`, `undefined`, `false`, ...), it throws an Error with the supplied `message`. When `test` passes, `true` is returned.
* @example
* <BR>
*
* ```javascript
* const { assert } from '@pezkuwi/util';
*
* assert(true, 'True should be true'); // passes
* assert(false, 'False should not be true'); // Error thrown
* assert(false, () => 'message'); // Error with 'message'
* ```
*/
export declare function assert(condition: unknown, message: string | MessageFn): asserts condition;
/**
* @name assertReturn
* @description Returns when the value is not undefined/null, otherwise throws assertion error
*/
export declare function assertReturn<T>(value: T | undefined | null, message: string | MessageFn): T;
/**
* @name assertUnreachable
* @description An assertion helper that ensures all codepaths are followed
*/
export declare function assertUnreachable(x: never): never;
export {};
+44
View File
@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assert = assert;
exports.assertReturn = assertReturn;
exports.assertUnreachable = assertUnreachable;
const function_js_1 = require("./is/function.js");
/**
* @name assert
* @summary Checks for a valid test, if not Error is thrown.
* @description
* Checks that `test` is a truthy value. If value is falsy (`null`, `undefined`, `false`, ...), it throws an Error with the supplied `message`. When `test` passes, `true` is returned.
* @example
* <BR>
*
* ```javascript
* const { assert } from '@pezkuwi/util';
*
* assert(true, 'True should be true'); // passes
* assert(false, 'False should not be true'); // Error thrown
* assert(false, () => 'message'); // Error with 'message'
* ```
*/
function assert(condition, message) {
if (!condition) {
throw new Error((0, function_js_1.isFunction)(message)
? message()
: message);
}
}
/**
* @name assertReturn
* @description Returns when the value is not undefined/null, otherwise throws assertion error
*/
function assertReturn(value, message) {
assert(value !== undefined && value !== null, message);
return value;
}
/**
* @name assertUnreachable
* @description An assertion helper that ensures all codepaths are followed
*/
function assertUnreachable(x) {
throw new Error(`This codepath should be unreachable. Unhandled input: ${x}`);
}
+90
View File
@@ -0,0 +1,90 @@
/**
* @name _0n
* @summary BigInt constant for 0.
*/
export declare const _0n: bigint;
/**
* @name _1n
* @summary BigInt constant for 1.
*/
export declare const _1n: bigint;
/**
* @name _2n
* @summary BigInt constant for 2.
*/
export declare const _2n: bigint;
/**
* @name _3n
* @summary BigInt constant for 3.
*/
export declare const _3n: bigint;
/**
* @name _4n
* @summary BigInt constant for 4.
*/
export declare const _4n: bigint;
/**
* @name _5n
* @summary BigInt constant for 5.
*/
export declare const _5n: bigint;
/**
* @name _6n
* @summary BigInt constant for 6.
*/
export declare const _6n: bigint;
/**
* @name _7n
* @summary BigInt constant for 7.
*/
export declare const _7n: bigint;
/**
* @name _8n
* @summary BigInt constant for 8.
*/
export declare const _8n: bigint;
/**
* @name _9n
* @summary BigInt constant for 9.
*/
export declare const _9n: bigint;
/**
* @name _10n
* @summary BigInt constant for 10.
*/
export declare const _10n: bigint;
/**
* @name _100n
* @summary BigInt constant for 100.
*/
export declare const _100n: bigint;
/**
* @name _1000n
* @summary BigInt constant for 1000.
*/
export declare const _1000n: bigint;
/**
* @name _1Mn
* @summary BigInt constant for 1,000,000 (million).
*/
export declare const _1Mn: bigint;
/**
* @name _1Bn
* @summary BigInt constant for 1,000,000,000 (billion).
*/
export declare const _1Bn: bigint;
/**
* @name _1Qn
* @summary BigInt constant for 1,000,000,000,000,000,000 (quitillion).
*/
export declare const _1Qn: bigint;
/**
* @name _2pow53n
* @summary BigInt constant for MAX_SAFE_INTEGER
*/
export declare const _2pow53n: bigint;
/**
* @name _sqrt2pow53n
* @summary BigInt constant for Math.sqrt(MAX_SAFE_INTEGER)
*/
export declare const _sqrt2pow53n: bigint;
+94
View File
@@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports._sqrt2pow53n = exports._2pow53n = exports._1Qn = exports._1Bn = exports._1Mn = exports._1000n = exports._100n = exports._10n = exports._9n = exports._8n = exports._7n = exports._6n = exports._5n = exports._4n = exports._3n = exports._2n = exports._1n = exports._0n = void 0;
const x_bigint_1 = require("@pezkuwi/x-bigint");
/**
* @name _0n
* @summary BigInt constant for 0.
*/
exports._0n = (0, x_bigint_1.BigInt)(0);
/**
* @name _1n
* @summary BigInt constant for 1.
*/
exports._1n = (0, x_bigint_1.BigInt)(1);
/**
* @name _2n
* @summary BigInt constant for 2.
*/
exports._2n = (0, x_bigint_1.BigInt)(2);
/**
* @name _3n
* @summary BigInt constant for 3.
*/
exports._3n = (0, x_bigint_1.BigInt)(3);
/**
* @name _4n
* @summary BigInt constant for 4.
*/
exports._4n = (0, x_bigint_1.BigInt)(4);
/**
* @name _5n
* @summary BigInt constant for 5.
*/
exports._5n = (0, x_bigint_1.BigInt)(5);
/**
* @name _6n
* @summary BigInt constant for 6.
*/
exports._6n = (0, x_bigint_1.BigInt)(6);
/**
* @name _7n
* @summary BigInt constant for 7.
*/
exports._7n = (0, x_bigint_1.BigInt)(7);
/**
* @name _8n
* @summary BigInt constant for 8.
*/
exports._8n = (0, x_bigint_1.BigInt)(8);
/**
* @name _9n
* @summary BigInt constant for 9.
*/
exports._9n = (0, x_bigint_1.BigInt)(9);
/**
* @name _10n
* @summary BigInt constant for 10.
*/
exports._10n = (0, x_bigint_1.BigInt)(10);
/**
* @name _100n
* @summary BigInt constant for 100.
*/
exports._100n = (0, x_bigint_1.BigInt)(100);
/**
* @name _1000n
* @summary BigInt constant for 1000.
*/
exports._1000n = (0, x_bigint_1.BigInt)(1_000);
/**
* @name _1Mn
* @summary BigInt constant for 1,000,000 (million).
*/
exports._1Mn = (0, x_bigint_1.BigInt)(1_000_000);
/**
* @name _1Bn
* @summary BigInt constant for 1,000,000,000 (billion).
*/
exports._1Bn = (0, x_bigint_1.BigInt)(1_000_000_000);
/**
* @name _1Qn
* @summary BigInt constant for 1,000,000,000,000,000,000 (quitillion).
*/
exports._1Qn = exports._1Bn * exports._1Bn;
/**
* @name _2pow53n
* @summary BigInt constant for MAX_SAFE_INTEGER
*/
exports._2pow53n = (0, x_bigint_1.BigInt)(Number.MAX_SAFE_INTEGER);
/**
* @name _sqrt2pow53n
* @summary BigInt constant for Math.sqrt(MAX_SAFE_INTEGER)
*/
exports._sqrt2pow53n = (0, x_bigint_1.BigInt)(94906265);
+2
View File
@@ -0,0 +1,2 @@
/** @internal */
export declare function createCmp<T>(cmp: (a: T, b: T) => boolean): (...items: T[]) => T;
+19
View File
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCmp = createCmp;
/** @internal */
function createCmp(cmp) {
return (...items) => {
const count = items.length;
if (count === 0) {
throw new Error('Must provide one or more arguments');
}
let result = items[0];
for (let i = 1; i < count; i++) {
if (cmp(items[i], result)) {
result = items[i];
}
}
return result;
};
}
+9
View File
@@ -0,0 +1,9 @@
/**
* @summary Utility methods to convert to and from `bigint` objects
*/
export { nMax, nMin } from './min.js';
export { nSqrt } from './sqrt.js';
export { nToBigInt } from './toBigInt.js';
export { nToHex } from './toHex.js';
export { nToU8a } from './toU8a.js';
export * from './consts.js';
+19
View File
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nToU8a = exports.nToHex = exports.nToBigInt = exports.nSqrt = exports.nMin = exports.nMax = void 0;
const tslib_1 = require("tslib");
/**
* @summary Utility methods to convert to and from `bigint` objects
*/
var min_js_1 = require("./min.js");
Object.defineProperty(exports, "nMax", { enumerable: true, get: function () { return min_js_1.nMax; } });
Object.defineProperty(exports, "nMin", { enumerable: true, get: function () { return min_js_1.nMin; } });
var sqrt_js_1 = require("./sqrt.js");
Object.defineProperty(exports, "nSqrt", { enumerable: true, get: function () { return sqrt_js_1.nSqrt; } });
var toBigInt_js_1 = require("./toBigInt.js");
Object.defineProperty(exports, "nToBigInt", { enumerable: true, get: function () { return toBigInt_js_1.nToBigInt; } });
var toHex_js_1 = require("./toHex.js");
Object.defineProperty(exports, "nToHex", { enumerable: true, get: function () { return toHex_js_1.nToHex; } });
var toU8a_js_1 = require("./toU8a.js");
Object.defineProperty(exports, "nToU8a", { enumerable: true, get: function () { return toU8a_js_1.nToU8a; } });
tslib_1.__exportStar(require("./consts.js"), exports);
+10
View File
@@ -0,0 +1,10 @@
/**
* @name nMax
* @summary Finds and returns the highest value in an array of bigint.
*/
export declare const nMax: (...items: bigint[]) => bigint;
/**
* @name nMin
* @summary Finds and returns the lowest value in an array of bigint.
*/
export declare const nMin: (...items: bigint[]) => bigint;
+14
View File
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nMin = exports.nMax = void 0;
const helpers_js_1 = require("./helpers.js");
/**
* @name nMax
* @summary Finds and returns the highest value in an array of bigint.
*/
exports.nMax = (0, helpers_js_1.createCmp)((a, b) => a > b);
/**
* @name nMin
* @summary Finds and returns the lowest value in an array of bigint.
*/
exports.nMin = (0, helpers_js_1.createCmp)((a, b) => a < b);
+7
View File
@@ -0,0 +1,7 @@
import type { BN } from '../bn/index.js';
import type { ToBigInt, ToBn } from '../types.js';
/**
* @name nSqrt
* @summary Calculates the integer square root of a bigint
*/
export declare function nSqrt<ExtToBn extends ToBn | ToBigInt>(value: ExtToBn | BN | bigint | string | number | null): bigint;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nSqrt = nSqrt;
const x_bigint_1 = require("@pezkuwi/x-bigint");
const consts_js_1 = require("./consts.js");
const toBigInt_js_1 = require("./toBigInt.js");
/**
* @name nSqrt
* @summary Calculates the integer square root of a bigint
*/
function nSqrt(value) {
const n = (0, toBigInt_js_1.nToBigInt)(value);
if (n < consts_js_1._0n) {
throw new Error('square root of negative numbers is not supported');
}
// https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/
// shortcut <= 2^53 - 1 to use the JS utils
if (n <= consts_js_1._2pow53n) {
// ~~ is more performant that Math.floor
return (0, x_bigint_1.BigInt)(~~Math.sqrt(Number(n)));
}
// Use sqrt(MAX_SAFE_INTEGER) as starting point. since we already know the
// output will be larger than this, we expect this to be a safe start
let x0 = consts_js_1._sqrt2pow53n;
while (true) {
const x1 = ((n / x0) + x0) >> consts_js_1._1n;
if (x0 === x1 || (x0 === (x1 - consts_js_1._1n))) {
return x0;
}
x0 = x1;
}
}
+7
View File
@@ -0,0 +1,7 @@
import type { BN } from '../bn/bn.js';
import type { ToBigInt, ToBn } from '../types.js';
/**
* @name nToBigInt
* @summary Creates a bigInt value from a BN, bigint, string (base 10 or hex) or number input.
*/
export declare function nToBigInt<ExtToBn extends ToBigInt | ToBn>(value?: ExtToBn | BN | bigint | string | number | null): bigint;
+28
View File
@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nToBigInt = nToBigInt;
const x_bigint_1 = require("@pezkuwi/x-bigint");
const toBigInt_js_1 = require("../hex/toBigInt.js");
const bn_js_1 = require("../is/bn.js");
const hex_js_1 = require("../is/hex.js");
const toBigInt_js_2 = require("../is/toBigInt.js");
const toBn_js_1 = require("../is/toBn.js");
/**
* @name nToBigInt
* @summary Creates a bigInt value from a BN, bigint, string (base 10 or hex) or number input.
*/
function nToBigInt(value) {
return typeof value === 'bigint'
? value
: !value
? (0, x_bigint_1.BigInt)(0)
: (0, hex_js_1.isHex)(value)
? (0, toBigInt_js_1.hexToBigInt)(value.toString())
: (0, bn_js_1.isBn)(value)
? (0, x_bigint_1.BigInt)(value.toString())
: (0, toBigInt_js_2.isToBigInt)(value)
? value.toBigInt()
: (0, toBn_js_1.isToBn)(value)
? (0, x_bigint_1.BigInt)(value.toBn().toString())
: (0, x_bigint_1.BigInt)(value);
}
+7
View File
@@ -0,0 +1,7 @@
import type { BN } from '../bn/bn.js';
import type { HexString, NumberOptions, ToBigInt, ToBn } from '../types.js';
/**
* @name nToHex
* @summary Creates a hex value from a bigint object.
*/
export declare function nToHex<ExtToBn extends ToBn | ToBigInt>(value?: ExtToBn | BN | bigint | number | null, { bitLength, isLe, isNegative }?: NumberOptions): HexString;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nToHex = nToHex;
const index_js_1 = require("../u8a/index.js");
const toU8a_js_1 = require("./toU8a.js");
/**
* @name nToHex
* @summary Creates a hex value from a bigint object.
*/
function nToHex(value, { bitLength = -1, isLe = false, isNegative = false } = {}) {
return (0, index_js_1.u8aToHex)((0, toU8a_js_1.nToU8a)(value || 0, { bitLength, isLe, isNegative }));
}
+7
View File
@@ -0,0 +1,7 @@
import type { BN } from '../bn/bn.js';
import type { NumberOptions, ToBigInt, ToBn } from '../types.js';
/**
* @name nToU8a
* @summary Creates a Uint8Array object from a bigint.
*/
export declare function nToU8a<ExtToBn extends ToBn | ToBigInt>(value?: ExtToBn | BN | bigint | number | null, { bitLength, isLe, isNegative }?: NumberOptions): Uint8Array;
+52
View File
@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nToU8a = nToU8a;
const x_bigint_1 = require("@pezkuwi/x-bigint");
const consts_js_1 = require("./consts.js");
const toBigInt_js_1 = require("./toBigInt.js");
const DIV = (0, x_bigint_1.BigInt)(256);
const NEG_MASK = (0, x_bigint_1.BigInt)(0xff);
function toU8a(value, isLe, isNegative) {
const arr = [];
const withSigned = isNegative && (value < consts_js_1._0n);
if (withSigned) {
value = (value + consts_js_1._1n) * -consts_js_1._1n;
}
while (value !== consts_js_1._0n) {
const mod = value % DIV;
const val = Number(withSigned
? mod ^ NEG_MASK
: mod);
if (isLe) {
arr.push(val);
}
else {
arr.unshift(val);
}
value = (value - mod) / DIV;
}
return Uint8Array.from(arr);
}
/**
* @name nToU8a
* @summary Creates a Uint8Array object from a bigint.
*/
function nToU8a(value, { bitLength = -1, isLe = true, isNegative = false } = {}) {
const valueBi = (0, toBigInt_js_1.nToBigInt)(value);
if (valueBi === consts_js_1._0n) {
return bitLength === -1
? new Uint8Array(1)
: new Uint8Array(Math.ceil((bitLength || 0) / 8));
}
const u8a = toU8a(valueBi, isLe, isNegative);
if (bitLength === -1) {
return u8a;
}
const byteLength = Math.ceil((bitLength || 0) / 8);
const output = new Uint8Array(byteLength);
if (isNegative) {
output.fill(0xff);
}
output.set(u8a, isLe ? 0 : byteLength - u8a.length);
return output;
}
+2
View File
@@ -0,0 +1,2 @@
import BN from 'bn.js';
export { BN };
+6
View File
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BN = void 0;
const tslib_1 = require("tslib");
const bn_js_1 = tslib_1.__importDefault(require("bn.js"));
exports.BN = bn_js_1.default;
+91
View File
@@ -0,0 +1,91 @@
import { BN } from './bn.js';
/**
* @name BN_ZERO
* @summary BN constant for 0.
*/
export declare const BN_ZERO: BN;
/**
* @name BN_ONE
* @summary BN constant for 1.
*/
export declare const BN_ONE: BN;
/**
* @name BN_TWO
* @summary BN constant for 2.
*/
export declare const BN_TWO: BN;
/**
* @name BN_THREE
* @summary BN constant for 3.
*/
export declare const BN_THREE: BN;
/**
* @name BN_FOUR
* @summary BN constant for 4.
*/
export declare const BN_FOUR: BN;
/**
* @name BN_FIVE
* @summary BN constant for 5.
*/
export declare const BN_FIVE: BN;
/**
* @name BN_SIX
* @summary BN constant for 6.
*/
export declare const BN_SIX: BN;
/**
* @name BN_SEVEN
* @summary BN constant for 7.
*/
export declare const BN_SEVEN: BN;
/**
* @name BN_EIGHT
* @summary BN constant for 8.
*/
export declare const BN_EIGHT: BN;
/**
* @name BN_NINE
* @summary BN constant for 9.
*/
export declare const BN_NINE: BN;
/**
* @name BN_TEN
* @summary BN constant for 10.
*/
export declare const BN_TEN: BN;
/**
* @name BN_HUNDRED
* @summary BN constant for 100.
*/
export declare const BN_HUNDRED: BN;
/**
* @name BN_THOUSAND
* @summary BN constant for 1,000.
*/
export declare const BN_THOUSAND: BN;
/**
* @name BN_MILLION
* @summary BN constant for 1,000,000.
*/
export declare const BN_MILLION: BN;
/**
* @name BN_BILLION
* @summary BN constant for 1,000,000,000.
*/
export declare const BN_BILLION: BN;
/**
* @name BN_QUINTILL
* @summary BN constant for 1,000,000,000,000,000,000.
*/
export declare const BN_QUINTILL: BN;
/**
* @name BN_MAX_INTEGER
* @summary BN constant for MAX_SAFE_INTEGER
*/
export declare const BN_MAX_INTEGER: BN;
/**
* @name BN_SQRT_MAX_INTEGER
* @summary BN constant for Math.sqrt(MAX_SAFE_INTEGER)
*/
export declare const BN_SQRT_MAX_INTEGER: BN;
+94
View File
@@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BN_SQRT_MAX_INTEGER = exports.BN_MAX_INTEGER = exports.BN_QUINTILL = exports.BN_BILLION = exports.BN_MILLION = exports.BN_THOUSAND = exports.BN_HUNDRED = exports.BN_TEN = exports.BN_NINE = exports.BN_EIGHT = exports.BN_SEVEN = exports.BN_SIX = exports.BN_FIVE = exports.BN_FOUR = exports.BN_THREE = exports.BN_TWO = exports.BN_ONE = exports.BN_ZERO = void 0;
const bn_js_1 = require("./bn.js");
/**
* @name BN_ZERO
* @summary BN constant for 0.
*/
exports.BN_ZERO = new bn_js_1.BN(0);
/**
* @name BN_ONE
* @summary BN constant for 1.
*/
exports.BN_ONE = new bn_js_1.BN(1);
/**
* @name BN_TWO
* @summary BN constant for 2.
*/
exports.BN_TWO = new bn_js_1.BN(2);
/**
* @name BN_THREE
* @summary BN constant for 3.
*/
exports.BN_THREE = new bn_js_1.BN(3);
/**
* @name BN_FOUR
* @summary BN constant for 4.
*/
exports.BN_FOUR = new bn_js_1.BN(4);
/**
* @name BN_FIVE
* @summary BN constant for 5.
*/
exports.BN_FIVE = new bn_js_1.BN(5);
/**
* @name BN_SIX
* @summary BN constant for 6.
*/
exports.BN_SIX = new bn_js_1.BN(6);
/**
* @name BN_SEVEN
* @summary BN constant for 7.
*/
exports.BN_SEVEN = new bn_js_1.BN(7);
/**
* @name BN_EIGHT
* @summary BN constant for 8.
*/
exports.BN_EIGHT = new bn_js_1.BN(8);
/**
* @name BN_NINE
* @summary BN constant for 9.
*/
exports.BN_NINE = new bn_js_1.BN(9);
/**
* @name BN_TEN
* @summary BN constant for 10.
*/
exports.BN_TEN = new bn_js_1.BN(10);
/**
* @name BN_HUNDRED
* @summary BN constant for 100.
*/
exports.BN_HUNDRED = new bn_js_1.BN(100);
/**
* @name BN_THOUSAND
* @summary BN constant for 1,000.
*/
exports.BN_THOUSAND = new bn_js_1.BN(1_000);
/**
* @name BN_MILLION
* @summary BN constant for 1,000,000.
*/
exports.BN_MILLION = new bn_js_1.BN(1_000_000);
/**
* @name BN_BILLION
* @summary BN constant for 1,000,000,000.
*/
exports.BN_BILLION = new bn_js_1.BN(1_000_000_000);
/**
* @name BN_QUINTILL
* @summary BN constant for 1,000,000,000,000,000,000.
*/
exports.BN_QUINTILL = exports.BN_BILLION.mul(exports.BN_BILLION);
/**
* @name BN_MAX_INTEGER
* @summary BN constant for MAX_SAFE_INTEGER
*/
exports.BN_MAX_INTEGER = new bn_js_1.BN(Number.MAX_SAFE_INTEGER);
/**
* @name BN_SQRT_MAX_INTEGER
* @summary BN constant for Math.sqrt(MAX_SAFE_INTEGER)
*/
exports.BN_SQRT_MAX_INTEGER = new bn_js_1.BN(94906265);
+1
View File
@@ -0,0 +1 @@
export { hexToBn as bnFromHex } from '../hex/toBn.js';
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bnFromHex = void 0;
var toBn_js_1 = require("../hex/toBn.js");
Object.defineProperty(exports, "bnFromHex", { enumerable: true, get: function () { return toBn_js_1.hexToBn; } });
+11
View File
@@ -0,0 +1,11 @@
/**
* @summary Utility methods to convert to and from `BN` objects
*/
export { BN } from './bn.js';
export { bnFromHex } from './fromHex.js';
export { bnMax, bnMin } from './min.js';
export { bnSqrt } from './sqrt.js';
export { bnToBn } from './toBn.js';
export { bnToHex } from './toHex.js';
export { bnToU8a } from './toU8a.js';
export * from './consts.js';
+23
View File
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bnToU8a = exports.bnToHex = exports.bnToBn = exports.bnSqrt = exports.bnMin = exports.bnMax = exports.bnFromHex = exports.BN = void 0;
const tslib_1 = require("tslib");
/**
* @summary Utility methods to convert to and from `BN` objects
*/
var bn_js_1 = require("./bn.js");
Object.defineProperty(exports, "BN", { enumerable: true, get: function () { return bn_js_1.BN; } });
var fromHex_js_1 = require("./fromHex.js");
Object.defineProperty(exports, "bnFromHex", { enumerable: true, get: function () { return fromHex_js_1.bnFromHex; } });
var min_js_1 = require("./min.js");
Object.defineProperty(exports, "bnMax", { enumerable: true, get: function () { return min_js_1.bnMax; } });
Object.defineProperty(exports, "bnMin", { enumerable: true, get: function () { return min_js_1.bnMin; } });
var sqrt_js_1 = require("./sqrt.js");
Object.defineProperty(exports, "bnSqrt", { enumerable: true, get: function () { return sqrt_js_1.bnSqrt; } });
var toBn_js_1 = require("./toBn.js");
Object.defineProperty(exports, "bnToBn", { enumerable: true, get: function () { return toBn_js_1.bnToBn; } });
var toHex_js_1 = require("./toHex.js");
Object.defineProperty(exports, "bnToHex", { enumerable: true, get: function () { return toHex_js_1.bnToHex; } });
var toU8a_js_1 = require("./toU8a.js");
Object.defineProperty(exports, "bnToU8a", { enumerable: true, get: function () { return toU8a_js_1.bnToU8a; } });
tslib_1.__exportStar(require("./consts.js"), exports);
+29
View File
@@ -0,0 +1,29 @@
import type { BN } from './bn.js';
/**
* @name bnMax
* @summary Finds and returns the highest value in an array of BNs.
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnMax } from '@pezkuwi/util';
*
* bnMax([new BN(1), new BN(3), new BN(2)]).toString(); // => '3'
* ```
*/
export declare const bnMax: (...items: BN[]) => BN;
/**
* @name bnMin
* @summary Finds and returns the smallest value in an array of BNs.
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnMin } from '@pezkuwi/util';
*
* bnMin([new BN(1), new BN(3), new BN(2)]).toString(); // => '1'
* ```
*/
export declare const bnMin: (...items: BN[]) => BN;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bnMin = exports.bnMax = void 0;
const helpers_js_1 = require("../bi/helpers.js");
/**
* @name bnMax
* @summary Finds and returns the highest value in an array of BNs.
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnMax } from '@pezkuwi/util';
*
* bnMax([new BN(1), new BN(3), new BN(2)]).toString(); // => '3'
* ```
*/
exports.bnMax = (0, helpers_js_1.createCmp)((a, b) => a.gt(b));
/**
* @name bnMin
* @summary Finds and returns the smallest value in an array of BNs.
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnMin } from '@pezkuwi/util';
*
* bnMin([new BN(1), new BN(3), new BN(2)]).toString(); // => '1'
* ```
*/
exports.bnMin = (0, helpers_js_1.createCmp)((a, b) => a.lt(b));
+16
View File
@@ -0,0 +1,16 @@
import type { ToBn } from '../types.js';
import { BN } from './bn.js';
/**
* @name bnSqrt
* @summary Calculates the integer square root of a BN
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnSqrt } from '@pezkuwi/util';
*
* bnSqrt(new BN(16)).toString(); // => '4'
* ```
*/
export declare function bnSqrt<ExtToBn extends ToBn>(value: ExtToBn | BN | bigint | string | number | null): BN;
+41
View File
@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bnSqrt = bnSqrt;
const bn_js_1 = require("./bn.js");
const consts_js_1 = require("./consts.js");
const toBn_js_1 = require("./toBn.js");
/**
* @name bnSqrt
* @summary Calculates the integer square root of a BN
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnSqrt } from '@pezkuwi/util';
*
* bnSqrt(new BN(16)).toString(); // => '4'
* ```
*/
function bnSqrt(value) {
const n = (0, toBn_js_1.bnToBn)(value);
if (n.isNeg()) {
throw new Error('square root of negative numbers is not supported');
}
// https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/
// shortcut <= 2^53 - 1 to use the JS utils
if (n.lte(consts_js_1.BN_MAX_INTEGER)) {
// ~~ More performant version of Math.floor
return new bn_js_1.BN(~~Math.sqrt(n.toNumber()));
}
// Use sqrt(MAX_SAFE_INTEGER) as starting point. since we already know the
// output will be larger than this, we expect this to be a safe start
let x0 = consts_js_1.BN_SQRT_MAX_INTEGER.clone();
while (true) {
const x1 = n.div(x0).iadd(x0).ishrn(1);
if (x0.eq(x1) || x0.eq(x1.sub(consts_js_1.BN_ONE))) {
return x0;
}
x0 = x1;
}
}
+19
View File
@@ -0,0 +1,19 @@
import type { ToBigInt, ToBn } from '../types.js';
import { BN } from './bn.js';
/**
* @name bnToBn
* @summary Creates a BN value from a BN, bigint, string (base 10 or hex) or number input.
* @description
* `null` inputs returns a `0x0` result, BN values returns the value, numbers returns a BN representation.
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnToBn } from '@pezkuwi/util';
*
* bnToBn(0x1234); // => BN(0x1234)
* bnToBn(new BN(0x1234)); // => BN(0x1234)
* ```
*/
export declare function bnToBn<ExtToBn extends ToBigInt | ToBn>(value?: ExtToBn | BN | bigint | string | number | null): BN;
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bnToBn = bnToBn;
const toBn_js_1 = require("../hex/toBn.js");
const bigInt_js_1 = require("../is/bigInt.js");
const hex_js_1 = require("../is/hex.js");
const toBigInt_js_1 = require("../is/toBigInt.js");
const toBn_js_2 = require("../is/toBn.js");
const bn_js_1 = require("./bn.js");
/**
* @name bnToBn
* @summary Creates a BN value from a BN, bigint, string (base 10 or hex) or number input.
* @description
* `null` inputs returns a `0x0` result, BN values returns the value, numbers returns a BN representation.
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnToBn } from '@pezkuwi/util';
*
* bnToBn(0x1234); // => BN(0x1234)
* bnToBn(new BN(0x1234)); // => BN(0x1234)
* ```
*/
function bnToBn(value) {
return value
? bn_js_1.BN.isBN(value)
? value
: (0, hex_js_1.isHex)(value)
? (0, toBn_js_1.hexToBn)(value.toString())
: (0, bigInt_js_1.isBigInt)(value)
? new bn_js_1.BN(value.toString())
: (0, toBn_js_2.isToBn)(value)
? value.toBn()
: (0, toBigInt_js_1.isToBigInt)(value)
? new bn_js_1.BN(value.toBigInt().toString())
: new bn_js_1.BN(value)
: new bn_js_1.BN(0);
}
+18
View File
@@ -0,0 +1,18 @@
import type { HexString, NumberOptions, ToBn } from '../types.js';
import type { BN } from './bn.js';
/**
* @name bnToHex
* @summary Creates a hex value from a BN.js bignumber object.
* @description
* `null` inputs returns a `0x` result, BN values return the actual value as a `0x` prefixed hex value. Anything that is not a BN object throws an error. With `bitLength` set, it fixes the number to the specified length.
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnToHex } from '@pezkuwi/util';
*
* bnToHex(new BN(0x123456)); // => '0x123456'
* ```
*/
export declare function bnToHex<ExtToBn extends ToBn>(value?: ExtToBn | BN | bigint | number | null, { bitLength, isLe, isNegative }?: NumberOptions): HexString;
+23
View File
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bnToHex = bnToHex;
const index_js_1 = require("../u8a/index.js");
const toU8a_js_1 = require("./toU8a.js");
/**
* @name bnToHex
* @summary Creates a hex value from a BN.js bignumber object.
* @description
* `null` inputs returns a `0x` result, BN values return the actual value as a `0x` prefixed hex value. Anything that is not a BN object throws an error. With `bitLength` set, it fixes the number to the specified length.
* @example
* <BR>
*
* ```javascript
* import BN from 'bn.js';
* import { bnToHex } from '@pezkuwi/util';
*
* bnToHex(new BN(0x123456)); // => '0x123456'
* ```
*/
function bnToHex(value, { bitLength = -1, isLe = false, isNegative = false } = {}) {
return (0, index_js_1.u8aToHex)((0, toU8a_js_1.bnToU8a)(value, { bitLength, isLe, isNegative }));
}
+17
View File
@@ -0,0 +1,17 @@
import type { NumberOptions, ToBn } from '../types.js';
import type { BN } from './bn.js';
/**
* @name bnToU8a
* @summary Creates a Uint8Array object from a BN.
* @description
* `null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `BN` input values return the actual bytes value converted to a `Uint8Array`. Optionally convert using little-endian format if `isLE` is set.
* @example
* <BR>
*
* ```javascript
* import { bnToU8a } from '@pezkuwi/util';
*
* bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
* ```
*/
export declare function bnToU8a<ExtToBn extends ToBn>(value?: ExtToBn | BN | bigint | number | null, { bitLength, isLe, isNegative }?: NumberOptions): Uint8Array;
+36
View File
@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bnToU8a = bnToU8a;
const toBn_js_1 = require("./toBn.js");
const DEFAULT_OPTS = { bitLength: -1, isLe: true, isNegative: false };
/**
* @name bnToU8a
* @summary Creates a Uint8Array object from a BN.
* @description
* `null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `BN` input values return the actual bytes value converted to a `Uint8Array`. Optionally convert using little-endian format if `isLE` is set.
* @example
* <BR>
*
* ```javascript
* import { bnToU8a } from '@pezkuwi/util';
*
* bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
* ```
*/
function bnToU8a(value, { bitLength = -1, isLe = true, isNegative = false } = DEFAULT_OPTS) {
const valueBn = (0, toBn_js_1.bnToBn)(value);
const byteLength = bitLength === -1
? Math.ceil(valueBn.bitLength() / 8)
: Math.ceil((bitLength || 0) / 8);
if (!value) {
return bitLength === -1
? new Uint8Array(1)
: new Uint8Array(byteLength);
}
const output = new Uint8Array(byteLength);
const bn = isNegative
? valueBn.toTwos(byteLength * 8)
: valueBn;
output.set(bn.toArray(isLe ? 'le' : 'be', byteLength), 0);
return output;
}
+4
View File
@@ -0,0 +1,4 @@
/**
* @summary Utility methods to convert to and from `Buffer` objects
*/
export { bufferToU8a } from './toU8a.js';
+8
View File
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bufferToU8a = void 0;
/**
* @summary Utility methods to convert to and from `Buffer` objects
*/
var toU8a_js_1 = require("./toU8a.js");
Object.defineProperty(exports, "bufferToU8a", { enumerable: true, get: function () { return toU8a_js_1.bufferToU8a; } });
+15
View File
@@ -0,0 +1,15 @@
/**
* @name bufferToU8a
* @summary Creates a Uint8Array value from a Buffer object.
* @description
* `null` inputs returns an empty result, `Buffer` values return the actual value as a `Uint8Array`. Anything that is not a `Buffer` object throws an error.
* @example
* <BR>
*
* ```javascript
* import { bufferToU8a } from '@pezkuwi/util';
*
* bufferToU8a(Buffer.from([1, 2, 3]));
* ```
*/
export declare function bufferToU8a(buffer?: Uint8Array | number[] | null): Uint8Array;
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bufferToU8a = bufferToU8a;
/**
* @name bufferToU8a
* @summary Creates a Uint8Array value from a Buffer object.
* @description
* `null` inputs returns an empty result, `Buffer` values return the actual value as a `Uint8Array`. Anything that is not a `Buffer` object throws an error.
* @example
* <BR>
*
* ```javascript
* import { bufferToU8a } from '@pezkuwi/util';
*
* bufferToU8a(Buffer.from([1, 2, 3]));
* ```
*/
function bufferToU8a(buffer) {
return new Uint8Array(buffer || []);
}
+28
View File
@@ -0,0 +1,28 @@
/**
* @summary Utility methods for this package are split into groups
*/
export { packageInfo } from './packageInfo.js';
export * from './array/index.js';
export * from './assert.js';
export * from './bi/index.js';
export * from './bn/index.js';
export * from './buffer/index.js';
export * from './compact/index.js';
export * from './detectPackage.js';
export * from './extractTime.js';
export * from './float/index.js';
export * from './format/index.js';
export * from './has.js';
export * from './hex/index.js';
export * from './is/index.js';
export * from './lazy.js';
export * from './logger.js';
export * from './memoize.js';
export * from './nextTick.js';
export * from './noop.js';
export * from './number/index.js';
export * from './object/index.js';
export * from './promisify.js';
export * from './string/index.js';
export * from './stringify.js';
export * from './u8a/index.js';
+33
View File
@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.packageInfo = void 0;
const tslib_1 = require("tslib");
/**
* @summary Utility methods for this package are split into groups
*/
var packageInfo_js_1 = require("./packageInfo.js");
Object.defineProperty(exports, "packageInfo", { enumerable: true, get: function () { return packageInfo_js_1.packageInfo; } });
tslib_1.__exportStar(require("./array/index.js"), exports);
tslib_1.__exportStar(require("./assert.js"), exports);
tslib_1.__exportStar(require("./bi/index.js"), exports);
tslib_1.__exportStar(require("./bn/index.js"), exports);
tslib_1.__exportStar(require("./buffer/index.js"), exports);
tslib_1.__exportStar(require("./compact/index.js"), exports);
tslib_1.__exportStar(require("./detectPackage.js"), exports);
tslib_1.__exportStar(require("./extractTime.js"), exports);
tslib_1.__exportStar(require("./float/index.js"), exports);
tslib_1.__exportStar(require("./format/index.js"), exports);
tslib_1.__exportStar(require("./has.js"), exports);
tslib_1.__exportStar(require("./hex/index.js"), exports);
tslib_1.__exportStar(require("./is/index.js"), exports);
tslib_1.__exportStar(require("./lazy.js"), exports);
tslib_1.__exportStar(require("./logger.js"), exports);
tslib_1.__exportStar(require("./memoize.js"), exports);
tslib_1.__exportStar(require("./nextTick.js"), exports);
tslib_1.__exportStar(require("./noop.js"), exports);
tslib_1.__exportStar(require("./number/index.js"), exports);
tslib_1.__exportStar(require("./object/index.js"), exports);
tslib_1.__exportStar(require("./promisify.js"), exports);
tslib_1.__exportStar(require("./string/index.js"), exports);
tslib_1.__exportStar(require("./stringify.js"), exports);
tslib_1.__exportStar(require("./u8a/index.js"), exports);
+13
View File
@@ -0,0 +1,13 @@
/**
* @name compactAddLength
* @description Adds a length prefix to the input value
* @example
* <BR>
*
* ```javascript
* import { compactAddLength } from '@pezkuwi/util';
*
* console.log(compactAddLength(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))); // Uint8Array([4 << 2, 0xde, 0xad, 0xbe, 0xef])
* ```
*/
export declare function compactAddLength(input: Uint8Array): Uint8Array;
+23
View File
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compactAddLength = compactAddLength;
const index_js_1 = require("../u8a/index.js");
const toU8a_js_1 = require("./toU8a.js");
/**
* @name compactAddLength
* @description Adds a length prefix to the input value
* @example
* <BR>
*
* ```javascript
* import { compactAddLength } from '@pezkuwi/util';
*
* console.log(compactAddLength(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))); // Uint8Array([4 << 2, 0xde, 0xad, 0xbe, 0xef])
* ```
*/
function compactAddLength(input) {
return (0, index_js_1.u8aConcatStrict)([
(0, toU8a_js_1.compactToU8a)(input.length),
input
]);
}
+3
View File
@@ -0,0 +1,3 @@
import type { BitLength } from './types.js';
/** @internal */
export declare const DEFAULT_BITLENGTH: BitLength;
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_BITLENGTH = void 0;
/** @internal */
exports.DEFAULT_BITLENGTH = 32;
+22
View File
@@ -0,0 +1,22 @@
import type { U8aLike } from '../types.js';
import { BN } from '../bn/index.js';
/**
* @name compactFromU8a
* @description Retrives the offset and encoded length from a compact-prefixed value
* @example
* <BR>
*
* ```javascript
* import { compactFromU8a } from '@pezkuwi/util';
*
* const [offset, length] = compactFromU8a(new Uint8Array([254, 255, 3, 0]));
*
* console.log('value offset=', offset, 'length=', length); // 4, 0xffff
* ```
*/
export declare function compactFromU8a(input: U8aLike): [number, BN];
/**
* @name compactFromU8aLim
* @description A limited version of [[compactFromU8a]], accepting only Uint8Array inputs for values <= 48 bits
*/
export declare function compactFromU8aLim(u8a: Uint8Array): [number, number];
+92
View File
@@ -0,0 +1,92 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compactFromU8a = compactFromU8a;
exports.compactFromU8aLim = compactFromU8aLim;
const index_js_1 = require("../bn/index.js");
const index_js_2 = require("../u8a/index.js");
/**
* @name compactFromU8a
* @description Retrives the offset and encoded length from a compact-prefixed value
* @example
* <BR>
*
* ```javascript
* import { compactFromU8a } from '@pezkuwi/util';
*
* const [offset, length] = compactFromU8a(new Uint8Array([254, 255, 3, 0]));
*
* console.log('value offset=', offset, 'length=', length); // 4, 0xffff
* ```
*/
function compactFromU8a(input) {
const u8a = (0, index_js_2.u8aToU8a)(input);
// The u8a is manually converted here for 1, 2 & 4 lengths, it is 2x faster
// than doing an additional call to u8aToBn (as with variable length)
switch (u8a[0] & 0b11) {
case 0b00:
return [1, new index_js_1.BN(u8a[0] >>> 2)];
case 0b01:
return [2, new index_js_1.BN((u8a[0] + (u8a[1] << 8)) >>> 2)];
case 0b10:
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return [4, new index_js_1.BN((u8a[0] + (u8a[1] << 8) + (u8a[2] << 16) + (u8a[3] * 0x1_00_00_00)) >>> 2)];
// 0b11
default: {
// add 5 to shifted (4 for base length, 1 for this byte)
const offset = (u8a[0] >>> 2) + 5;
// we unroll the loop
switch (offset) {
// there still could be 4 bytes data, similar to 0b10 above (with offsets)
case 5:
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return [5, new index_js_1.BN(u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + (u8a[4] * 0x1_00_00_00))];
case 6:
return [6, new index_js_1.BN(u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8)) * 0x1_00_00_00))];
// 6 bytes data is the maximum, 48 bits (56 would overflow)
case 7:
return [7, new index_js_1.BN(u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8) + (u8a[6] << 16)) * 0x1_00_00_00))];
// for anything else, use the non-unrolled version
default:
return [offset, (0, index_js_2.u8aToBn)(u8a.subarray(1, offset))];
}
}
}
}
/**
* @name compactFromU8aLim
* @description A limited version of [[compactFromU8a]], accepting only Uint8Array inputs for values <= 48 bits
*/
function compactFromU8aLim(u8a) {
// The u8a is manually converted here for 1, 2 & 4 lengths, it is 2x faster
// than doing an additional call to u8aToBn (as with variable length)
switch (u8a[0] & 0b11) {
case 0b00:
return [1, u8a[0] >>> 2];
case 0b01:
return [2, (u8a[0] + (u8a[1] << 8)) >>> 2];
case 0b10:
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return [4, (u8a[0] + (u8a[1] << 8) + (u8a[2] << 16) + (u8a[3] * 0x1_00_00_00)) >>> 2];
// 0b11
default: {
// add 5 to shifted (4 for base length, 1 for this byte)
// we unroll the loop
switch ((u8a[0] >>> 2) + 5) {
// there still could be 4 bytes data, similar to 0b10 above (with offsets)
case 5:
return [5, u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + (u8a[4] * 0x1_00_00_00)];
case 6:
return [6, u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8)) * 0x1_00_00_00)];
// 6 bytes data is the maximum, 48 bits (56 would overflow)
case 7:
return [7, u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8) + (u8a[6] << 16)) * 0x1_00_00_00)];
// for anything else, we are above the actual MAX_SAFE_INTEGER - bail out
default:
throw new Error('Compact input is > Number.MAX_SAFE_INTEGER');
}
}
}
}
+24
View File
@@ -0,0 +1,24 @@
/**
* @description
* Encoding and decoding of parity-codec compact numbers. The codec is created
* to take up the least amount of space for a specific number. It performs the
* same function as Length, however differs in that it uses a variable number of
* bytes to do the actual encoding. From the Rust implementation for compact
* encoding:
*
* 0b00 00 00 00 / 00 00 00 00 / 00 00 00 00 / 00 00 00 00
* (0 ... 2**6 - 1) (u8)
* xx xx xx 00
* (2**6 ... 2**14 - 1) (u8, u16) low LH high
* yL yL yL 01 / yH yH yH yL
* (2**14 ... 2**30 - 1) (u16, u32) low LMMH high
* zL zL zL 10 / zM zM zM zL / zM zM zM zM / zH zH zH zM
* (2**30 ... 2**536 - 1) (u32, u64, u128, U256, U512, U520) straight LE-encoded
* nn nn nn 11 [ / zz zz zz zz ]{4 + n}
*
* Note: we use *LOW BITS* of the LSB in LE encoding to encode the 2 bit key.
*/
export { compactAddLength } from './addLength.js';
export { compactFromU8a, compactFromU8aLim } from './fromU8a.js';
export { compactStripLength } from './stripLength.js';
export { compactToU8a } from './toU8a.js';
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compactToU8a = exports.compactStripLength = exports.compactFromU8aLim = exports.compactFromU8a = exports.compactAddLength = void 0;
/**
* @description
* Encoding and decoding of parity-codec compact numbers. The codec is created
* to take up the least amount of space for a specific number. It performs the
* same function as Length, however differs in that it uses a variable number of
* bytes to do the actual encoding. From the Rust implementation for compact
* encoding:
*
* 0b00 00 00 00 / 00 00 00 00 / 00 00 00 00 / 00 00 00 00
* (0 ... 2**6 - 1) (u8)
* xx xx xx 00
* (2**6 ... 2**14 - 1) (u8, u16) low LH high
* yL yL yL 01 / yH yH yH yL
* (2**14 ... 2**30 - 1) (u16, u32) low LMMH high
* zL zL zL 10 / zM zM zM zL / zM zM zM zM / zH zH zH zM
* (2**30 ... 2**536 - 1) (u32, u64, u128, U256, U512, U520) straight LE-encoded
* nn nn nn 11 [ / zz zz zz zz ]{4 + n}
*
* Note: we use *LOW BITS* of the LSB in LE encoding to encode the 2 bit key.
*/
var addLength_js_1 = require("./addLength.js");
Object.defineProperty(exports, "compactAddLength", { enumerable: true, get: function () { return addLength_js_1.compactAddLength; } });
var fromU8a_js_1 = require("./fromU8a.js");
Object.defineProperty(exports, "compactFromU8a", { enumerable: true, get: function () { return fromU8a_js_1.compactFromU8a; } });
Object.defineProperty(exports, "compactFromU8aLim", { enumerable: true, get: function () { return fromU8a_js_1.compactFromU8aLim; } });
var stripLength_js_1 = require("./stripLength.js");
Object.defineProperty(exports, "compactStripLength", { enumerable: true, get: function () { return stripLength_js_1.compactStripLength; } });
var toU8a_js_1 = require("./toU8a.js");
Object.defineProperty(exports, "compactToU8a", { enumerable: true, get: function () { return toU8a_js_1.compactToU8a; } });
+13
View File
@@ -0,0 +1,13 @@
/**
* @name compactStripLength
* @description Removes the length prefix, returning both the total length (including the value + compact encoding) and the decoded value with the correct length
* @example
* <BR>
*
* ```javascript
* import { compactStripLength } from '@pezkuwi/util';
*
* console.log(compactStripLength(new Uint8Array([2 << 2, 0xde, 0xad]))); // [2, Uint8Array[0xde, 0xad]]
* ```
*/
export declare function compactStripLength(input: Uint8Array): [number, Uint8Array];
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compactStripLength = compactStripLength;
const fromU8a_js_1 = require("./fromU8a.js");
/**
* @name compactStripLength
* @description Removes the length prefix, returning both the total length (including the value + compact encoding) and the decoded value with the correct length
* @example
* <BR>
*
* ```javascript
* import { compactStripLength } from '@pezkuwi/util';
*
* console.log(compactStripLength(new Uint8Array([2 << 2, 0xde, 0xad]))); // [2, Uint8Array[0xde, 0xad]]
* ```
*/
function compactStripLength(input) {
const [offset, length] = (0, fromU8a_js_1.compactFromU8a)(input);
const total = offset + length.toNumber();
return [
total,
input.subarray(offset, total)
];
}
+14
View File
@@ -0,0 +1,14 @@
import { BN } from '../bn/index.js';
/**
* @name compactToU8a
* @description Encodes a number into a compact representation
* @example
* <BR>
*
* ```javascript
* import { compactToU8a } from '@pezkuwi/util';
*
* console.log(compactToU8a(511, 32)); // Uint8Array([0b11111101, 0b00000111])
* ```
*/
export declare function compactToU8a(value: BN | bigint | number): Uint8Array;
+48
View File
@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compactToU8a = compactToU8a;
const index_js_1 = require("../bn/index.js");
const index_js_2 = require("../u8a/index.js");
const MAX_U8 = index_js_1.BN_TWO.pow(new index_js_1.BN(8 - 2)).isub(index_js_1.BN_ONE);
const MAX_U16 = index_js_1.BN_TWO.pow(new index_js_1.BN(16 - 2)).isub(index_js_1.BN_ONE);
const MAX_U32 = index_js_1.BN_TWO.pow(new index_js_1.BN(32 - 2)).isub(index_js_1.BN_ONE);
const BL_16 = { bitLength: 16 };
const BL_32 = { bitLength: 32 };
/**
* @name compactToU8a
* @description Encodes a number into a compact representation
* @example
* <BR>
*
* ```javascript
* import { compactToU8a } from '@pezkuwi/util';
*
* console.log(compactToU8a(511, 32)); // Uint8Array([0b11111101, 0b00000111])
* ```
*/
function compactToU8a(value) {
const bn = (0, index_js_1.bnToBn)(value);
if (bn.lte(MAX_U8)) {
return new Uint8Array([bn.toNumber() << 2]);
}
else if (bn.lte(MAX_U16)) {
return (0, index_js_1.bnToU8a)(bn.shln(2).iadd(index_js_1.BN_ONE), BL_16);
}
else if (bn.lte(MAX_U32)) {
return (0, index_js_1.bnToU8a)(bn.shln(2).iadd(index_js_1.BN_TWO), BL_32);
}
const u8a = (0, index_js_1.bnToU8a)(bn);
let length = u8a.length;
// adjust to the minimum number of bytes
while (u8a[length - 1] === 0) {
length--;
}
if (length < 4) {
throw new Error('Invalid length, previous checks match anything less than 2^30');
}
return (0, index_js_2.u8aConcatStrict)([
// subtract 4 as minimum (also catered for in decoding)
new Uint8Array([((length - 4) << 2) + 0b11]),
u8a.subarray(0, length)
]);
}
+1
View File
@@ -0,0 +1 @@
export type BitLength = 8 | 16 | 32 | 64 | 128 | 256;
+2
View File
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
+17
View File
@@ -0,0 +1,17 @@
interface VersionPath {
path: string;
type: string;
version: string;
}
interface PackageInfo extends VersionPath {
name: string;
}
type FnString = () => string | undefined;
export declare const POLKADOTJS_DISABLE_ESM_CJS_WARNING_FLAG = "POLKADOTJS_DISABLE_ESM_CJS_WARNING";
/**
* @name detectPackage
* @summary Checks that a specific package is only imported once
* @description A `@pezkuwi/*` version detection utility, checking for one occurrence of a package in addition to checking for dependency versions.
*/
export declare function detectPackage({ name, path, type, version }: PackageInfo, pathOrFn?: FnString | string | false | null, deps?: PackageInfo[]): void;
export {};
+100
View File
@@ -0,0 +1,100 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.POLKADOTJS_DISABLE_ESM_CJS_WARNING_FLAG = void 0;
exports.detectPackage = detectPackage;
const x_global_1 = require("@pezkuwi/x-global");
const function_js_1 = require("./is/function.js");
const DEDUPE = 'Either remove and explicitly install matching versions or dedupe using your package manager.\nThe following conflicting packages were found:';
exports.POLKADOTJS_DISABLE_ESM_CJS_WARNING_FLAG = 'POLKADOTJS_DISABLE_ESM_CJS_WARNING';
/** @internal */
function getEntry(name) {
const _global = x_global_1.xglobal;
if (!_global.__polkadotjs) {
_global.__polkadotjs = {};
}
if (!_global.__polkadotjs[name]) {
_global.__polkadotjs[name] = [];
}
return _global.__polkadotjs[name];
}
/** @internal */
function formatDisplay(all, fmt) {
let max = 0;
for (let i = 0, count = all.length; i < count; i++) {
max = Math.max(max, all[i].version.length);
}
return all
.map((d) => `\t${fmt(d.version.padEnd(max), d).join('\t')}`)
.join('\n');
}
/** @internal */
function formatInfo(version, { name }) {
return [
version,
name
];
}
/** @internal */
function formatVersion(version, { path, type }) {
let extracted;
if (path && path.length >= 5) {
const nmIndex = path.indexOf('node_modules');
extracted = nmIndex === -1
? path
: path.substring(nmIndex);
}
else {
extracted = '<unknown>';
}
return [
`${`${type || ''}`.padStart(3)} ${version}`,
extracted
];
}
/** @internal */
function getPath(infoPath, pathOrFn) {
if (infoPath) {
return infoPath;
}
else if ((0, function_js_1.isFunction)(pathOrFn)) {
try {
return pathOrFn() || '';
}
catch {
return '';
}
}
return pathOrFn || '';
}
/** @internal */
function warn(pre, all, fmt) {
console.warn(`${pre}\n${DEDUPE}\n${formatDisplay(all, fmt)}`);
}
/**
* @name detectPackage
* @summary Checks that a specific package is only imported once
* @description A `@pezkuwi/*` version detection utility, checking for one occurrence of a package in addition to checking for dependency versions.
*/
function detectPackage({ name, path, type, version }, pathOrFn, deps = []) {
if (!name.startsWith('@pezkuwi')) {
throw new Error(`Invalid package descriptor ${name}`);
}
const entry = getEntry(name);
entry.push({ path: getPath(path, pathOrFn), type, version });
// if we have more than one entry at DIFFERENT version types then warn. If there is
// more than one entry at the same version and ESM/CJS dual warnings are disabled,
// then do not display warnings
const entriesSameVersion = entry.every((e) => e.version === version);
const esmCjsWarningDisabled = x_global_1.xglobal.process?.env?.[exports.POLKADOTJS_DISABLE_ESM_CJS_WARNING_FLAG] === '1';
const multipleEntries = entry.length !== 1;
const disableWarnings = esmCjsWarningDisabled && entriesSameVersion;
if (multipleEntries && !disableWarnings) {
warn(`${name} has multiple versions, ensure that there is only one installed.`, entry, formatVersion);
}
else {
const mismatches = deps.filter((d) => d && d.version !== version);
if (mismatches.length) {
warn(`${name} requires direct dependencies exactly matching version ${version}.`, mismatches, formatInfo);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
import type { Time } from './types.js';
/**
* @name extractTime
* @summary Convert a quantity of seconds to Time array representing accumulated {days, minutes, hours, seconds, milliseconds}
* @example
* <BR>
*
* ```javascript
* import { extractTime } from '@pezkuwi/util';
*
* const { days, minutes, hours, seconds, milliseconds } = extractTime(6000); // 0, 0, 10, 0, 0
* ```
*/
export declare function extractTime(milliseconds?: number): Time;
+56
View File
@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractTime = extractTime;
const MIN_MS = 60 * 1000;
const HR_MS = MIN_MS * 60;
const DAY_MS = HR_MS * 24;
const ZERO = { days: 0, hours: 0, milliseconds: 0, minutes: 0, seconds: 0 };
/** @internal */
function add(a, b) {
return {
days: (a.days || 0) + b.days,
hours: (a.hours || 0) + b.hours,
milliseconds: (a.milliseconds || 0) + b.milliseconds,
minutes: (a.minutes || 0) + b.minutes,
seconds: (a.seconds || 0) + b.seconds
};
}
/** @internal */
function extractSecs(ms) {
const s = ms / 1000;
if (s < 60) {
const seconds = ~~s;
return add({ seconds }, extractTime(ms - (seconds * 1000)));
}
const m = s / 60;
if (m < 60) {
const minutes = ~~m;
return add({ minutes }, extractTime(ms - (minutes * MIN_MS)));
}
const h = m / 60;
if (h < 24) {
const hours = ~~h;
return add({ hours }, extractTime(ms - (hours * HR_MS)));
}
const days = ~~(h / 24);
return add({ days }, extractTime(ms - (days * DAY_MS)));
}
/**
* @name extractTime
* @summary Convert a quantity of seconds to Time array representing accumulated {days, minutes, hours, seconds, milliseconds}
* @example
* <BR>
*
* ```javascript
* import { extractTime } from '@pezkuwi/util';
*
* const { days, minutes, hours, seconds, milliseconds } = extractTime(6000); // 0, 0, 10, 0, 0
* ```
*/
function extractTime(milliseconds) {
return !milliseconds
? ZERO
: milliseconds < 1000
? add({ milliseconds }, ZERO)
: extractSecs(milliseconds);
}
+1
View File
@@ -0,0 +1 @@
export { floatToU8a } from './toU8a.js';
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.floatToU8a = void 0;
var toU8a_js_1 = require("./toU8a.js");
Object.defineProperty(exports, "floatToU8a", { enumerable: true, get: function () { return toU8a_js_1.floatToU8a; } });
+11
View File
@@ -0,0 +1,11 @@
interface Options {
bitLength?: 32 | 64;
isLe?: boolean;
}
/**
* @name floatToU8a
* @description Converts a float into a U8a representation (While we don't use BE in SCALE
* we still allow for either representation, although, as elsewhere, isLe is default)
*/
export declare function floatToU8a(value?: String | string | number | Number, { bitLength, isLe }?: Options): Uint8Array;
export {};
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.floatToU8a = floatToU8a;
/**
* @name floatToU8a
* @description Converts a float into a U8a representation (While we don't use BE in SCALE
* we still allow for either representation, although, as elsewhere, isLe is default)
*/
function floatToU8a(value = 0.0, { bitLength = 32, isLe = true } = {}) {
if (bitLength !== 32 && bitLength !== 64) {
throw new Error('Invalid bitLength provided, expected 32 or 64');
}
const result = new Uint8Array(bitLength / 8);
const dv = new DataView(result.buffer, result.byteOffset);
if (bitLength === 32) {
dv.setFloat32(0, Number(value), isLe);
}
else {
dv.setFloat64(0, Number(value), isLe);
}
return result;
}
+54
View File
@@ -0,0 +1,54 @@
import type { BN } from '../bn/bn.js';
import type { SiDef, ToBn } from '../types.js';
interface Defaults {
decimals: number;
unit: string;
}
interface SetDefaults {
decimals?: number[] | number;
unit?: string[] | string;
}
interface Options {
/**
* @description The number of decimals
*/
decimals?: number;
/**
* @description Format the number with this specific unit
*/
forceUnit?: string;
/**
* @description Returns value using all available decimals
*/
withAll?: boolean;
/**
* @description Format with SI, i.e. m/M/etc. (default = true)
*/
withSi?: boolean;
/**
* @description Format with full SI, i.e. mili/Mega/etc.
*/
withSiFull?: boolean;
/**
* @description Add the unit (useful in Balance formats)
*/
withUnit?: boolean | string;
/**
* @description Returns all trailing zeros, otherwise removes (default = true)
*/
withZero?: boolean;
/**
* @description The locale to use
*/
locale?: string;
}
interface BalanceFormatter {
<ExtToBn extends ToBn>(input?: number | string | BN | bigint | ExtToBn, options?: Options): string;
calcSi(text: string, decimals?: number): SiDef;
findSi(type: string): SiDef;
getDefaults(): Defaults;
getOptions(decimals?: number): SiDef[];
setDefaults(defaults: SetDefaults): void;
}
export declare const formatBalance: BalanceFormatter;
export {};
+88
View File
@@ -0,0 +1,88 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatBalance = void 0;
const toBn_js_1 = require("../bn/toBn.js");
const boolean_js_1 = require("../is/boolean.js");
const formatDecimal_js_1 = require("./formatDecimal.js");
const getSeparator_js_1 = require("./getSeparator.js");
const si_js_1 = require("./si.js");
const DEFAULT_DECIMALS = 0;
const DEFAULT_UNIT = si_js_1.SI[si_js_1.SI_MID].text;
let defaultDecimals = DEFAULT_DECIMALS;
let defaultUnit = DEFAULT_UNIT;
function _formatBalance(input, { decimals = defaultDecimals, forceUnit, locale = 'en', withAll = false, withSi = true, withSiFull = false, withUnit = true, withZero = true } = {}) {
// we only work with string inputs here - convert anything
// into the string-only value
let text = (0, toBn_js_1.bnToBn)(input).toString();
if (text.length === 0 || text === '0') {
return '0';
}
// strip the negative sign so we can work with clean groupings, re-add this in the
// end when we return the result (from here on we work with positive numbers)
let sign = '';
if (text[0].startsWith('-')) {
sign = '-';
text = text.substring(1);
}
// We start at midpoint (8) minus 1 - this means that values display as
// 123.4567 instead of 0.1234 k (so we always have the most relevant).
const si = (0, si_js_1.calcSi)(text, decimals, forceUnit);
const mid = text.length - (decimals + si.power);
const pre = mid <= 0 ? '0' : text.substring(0, mid);
// get the post from the midpoint onward and then first add max decimals
// before trimming to the correct (calculated) amount of decimals again
let post = text
.padStart(mid < 0 ? decimals : 1, '0')
.substring(mid < 0 ? 0 : mid)
.padEnd(withAll ? Math.max(decimals, 4) : 4, '0')
.substring(0, withAll ? Math.max(4, decimals + si.power) : 4);
// remove all trailing 0's (if required via flag)
if (!withZero) {
let end = post.length - 1;
// This looks inefficient, however it is better to do the checks and
// only make one final slice than it is to do it in multiples
do {
if (post[end] === '0') {
end--;
}
} while (post[end] === '0');
post = post.substring(0, end + 1);
}
// the display unit
const unit = (0, boolean_js_1.isBoolean)(withUnit)
? si_js_1.SI[si_js_1.SI_MID].text
: withUnit;
// format the units for display based on the flags
const units = withSi || withSiFull
? si.value === '-'
? withUnit
? ` ${unit}`
: ''
: ` ${withSiFull ? `${si.text}${withUnit ? ' ' : ''}` : si.value}${withUnit ? unit : ''}`
: '';
const { decimal, thousand } = (0, getSeparator_js_1.getSeparator)(locale);
return `${sign}${(0, formatDecimal_js_1.formatDecimal)(pre, thousand)}${post && `${decimal}${post}`}${units}`;
}
exports.formatBalance = _formatBalance;
exports.formatBalance.calcSi = (text, decimals = defaultDecimals) => (0, si_js_1.calcSi)(text, decimals);
exports.formatBalance.findSi = si_js_1.findSi;
exports.formatBalance.getDefaults = () => {
return {
decimals: defaultDecimals,
unit: defaultUnit
};
};
exports.formatBalance.getOptions = (decimals = defaultDecimals) => {
return si_js_1.SI.filter(({ power }) => power < 0
? (decimals + power) >= 0
: true);
};
exports.formatBalance.setDefaults = ({ decimals, unit }) => {
defaultDecimals = (Array.isArray(decimals)
? decimals[0]
: decimals) ?? defaultDecimals;
defaultUnit = (Array.isArray(unit)
? unit[0]
: unit) ?? defaultUnit;
si_js_1.SI[si_js_1.SI_MID].text = defaultUnit;
};
+5
View File
@@ -0,0 +1,5 @@
/**
* @name formatDate
* @description Formats a date in CCYY-MM-DD HH:MM:SS format
*/
export declare function formatDate(date: Date): string;
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatDate = formatDate;
/** @internal */
function zeroPad(value) {
return value.toString().padStart(2, '0');
}
/**
* @name formatDate
* @description Formats a date in CCYY-MM-DD HH:MM:SS format
*/
function formatDate(date) {
const year = date.getFullYear().toString();
const month = zeroPad((date.getMonth() + 1));
const day = zeroPad(date.getDate());
const hour = zeroPad(date.getHours());
const minute = zeroPad(date.getMinutes());
const second = zeroPad(date.getSeconds());
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
+5
View File
@@ -0,0 +1,5 @@
/**
* @name formatDecimal
* @description Formats a number into string format with thousand separators
*/
export declare function formatDecimal(value: string, separator?: string): string;
+19
View File
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatDecimal = formatDecimal;
const NUMBER_REGEX = new RegExp('(\\d+?)(?=(\\d{3})+(?!\\d)|$)', 'g');
/**
* @name formatDecimal
* @description Formats a number into string format with thousand separators
*/
function formatDecimal(value, separator = ',') {
// We can do this by adjusting the regx, however for the sake of clarity
// we rather strip and re-add the negative sign in the output
const isNegative = value[0].startsWith('-');
const matched = isNegative
? value.substring(1).match(NUMBER_REGEX)
: value.match(NUMBER_REGEX);
return matched
? `${isNegative ? '-' : ''}${matched.join(separator)}`
: value;
}
+7
View File
@@ -0,0 +1,7 @@
import type { BN } from '../bn/bn.js';
import type { ToBn } from '../types.js';
/**
* @name formatElapsed
* @description Formats an elapsed value into s, m, h or day segments
*/
export declare function formatElapsed<ExtToBn extends ToBn>(now?: Date | null, value?: bigint | BN | ExtToBn | Date | number | null): string;
+30
View File
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatElapsed = formatElapsed;
const toBn_js_1 = require("../bn/toBn.js");
/** @internal */
function formatValue(elapsed) {
if (elapsed < 15) {
return `${elapsed.toFixed(1)}s`;
}
else if (elapsed < 60) {
return `${elapsed | 0}s`;
}
else if (elapsed < 3600) {
return `${elapsed / 60 | 0}m`;
}
return `${elapsed / 3600 | 0}h`;
}
/**
* @name formatElapsed
* @description Formats an elapsed value into s, m, h or day segments
*/
function formatElapsed(now, value) {
const tsNow = now?.getTime() || 0;
const tsValue = value instanceof Date
? value.getTime()
: (0, toBn_js_1.bnToBn)(value).toNumber();
return (tsNow && tsValue)
? formatValue(Math.max(Math.abs(tsNow - tsValue), 0) / 1000)
: '0.0s';
}
+14
View File
@@ -0,0 +1,14 @@
import type { BN } from '../bn/bn.js';
import type { ToBn } from '../types.js';
interface Options {
/**
* @description The locale to use
*/
locale?: string;
}
/**
* @name formatNumber
* @description Formats a number into string format with thousand separators
*/
export declare function formatNumber<ExtToBn extends ToBn>(value?: ExtToBn | BN | bigint | number | null, { locale }?: Options): string;
export {};
+14
View File
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatNumber = formatNumber;
const toBn_js_1 = require("../bn/toBn.js");
const formatDecimal_js_1 = require("./formatDecimal.js");
const getSeparator_js_1 = require("./getSeparator.js");
/**
* @name formatNumber
* @description Formats a number into string format with thousand separators
*/
function formatNumber(value, { locale = 'en' } = {}) {
const { thousand } = (0, getSeparator_js_1.getSeparator)(locale);
return (0, formatDecimal_js_1.formatDecimal)((0, toBn_js_1.bnToBn)(value).toString(), thousand);
}
+9
View File
@@ -0,0 +1,9 @@
/**
* Get the decimal and thousand separator of a locale
* @param locale
* @returns {decimal: string, thousand: string}
*/
export declare function getSeparator(locale?: string): {
thousand: string;
decimal: string;
};
+14
View File
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSeparator = getSeparator;
/**
* Get the decimal and thousand separator of a locale
* @param locale
* @returns {decimal: string, thousand: string}
*/
function getSeparator(locale) {
return {
decimal: (0.1).toLocaleString(locale, { useGrouping: false }).charAt(1),
thousand: (1000).toLocaleString(locale, { useGrouping: true }).replace(/\d/g, '').charAt(0)
};
}
+6
View File
@@ -0,0 +1,6 @@
export { formatBalance } from './formatBalance.js';
export { formatDate } from './formatDate.js';
export { formatDecimal } from './formatDecimal.js';
export { formatElapsed } from './formatElapsed.js';
export { formatNumber } from './formatNumber.js';
export { calcSi, findSi } from './si.js';
+16
View File
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findSi = exports.calcSi = exports.formatNumber = exports.formatElapsed = exports.formatDecimal = exports.formatDate = exports.formatBalance = void 0;
var formatBalance_js_1 = require("./formatBalance.js");
Object.defineProperty(exports, "formatBalance", { enumerable: true, get: function () { return formatBalance_js_1.formatBalance; } });
var formatDate_js_1 = require("./formatDate.js");
Object.defineProperty(exports, "formatDate", { enumerable: true, get: function () { return formatDate_js_1.formatDate; } });
var formatDecimal_js_1 = require("./formatDecimal.js");
Object.defineProperty(exports, "formatDecimal", { enumerable: true, get: function () { return formatDecimal_js_1.formatDecimal; } });
var formatElapsed_js_1 = require("./formatElapsed.js");
Object.defineProperty(exports, "formatElapsed", { enumerable: true, get: function () { return formatElapsed_js_1.formatElapsed; } });
var formatNumber_js_1 = require("./formatNumber.js");
Object.defineProperty(exports, "formatNumber", { enumerable: true, get: function () { return formatNumber_js_1.formatNumber; } });
var si_js_1 = require("./si.js");
Object.defineProperty(exports, "calcSi", { enumerable: true, get: function () { return si_js_1.calcSi; } });
Object.defineProperty(exports, "findSi", { enumerable: true, get: function () { return si_js_1.findSi; } });
+9
View File
@@ -0,0 +1,9 @@
import type { SiDef } from '../types.js';
/** @internal */
export declare const SI_MID = 8;
/** @internal */
export declare const SI: SiDef[];
/** @internal */
export declare function findSi(type: string): SiDef;
/** @internal */
export declare function calcSi(text: string, decimals: number, forceUnit?: string): SiDef;
+45
View File
@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SI = exports.SI_MID = void 0;
exports.findSi = findSi;
exports.calcSi = calcSi;
/** @internal */
exports.SI_MID = 8;
/** @internal */
exports.SI = [
{ power: -24, text: 'yocto', value: 'y' },
{ power: -21, text: 'zepto', value: 'z' },
{ power: -18, text: 'atto', value: 'a' },
{ power: -15, text: 'femto', value: 'f' },
{ power: -12, text: 'pico', value: 'p' },
{ power: -9, text: 'nano', value: 'n' },
{ power: -6, text: 'micro', value: 'µ' },
{ power: -3, text: 'milli', value: 'm' },
{ power: 0, text: 'Unit', value: '-' }, // position 8
{ power: 3, text: 'Kilo', value: 'k' },
{ power: 6, text: 'Mill', value: 'M' }, // Mega, M
{ power: 9, text: 'Bill', value: 'B' }, // Giga, G
{ power: 12, text: 'Tril', value: 'T' }, // Tera, T
{ power: 15, text: 'Peta', value: 'P' },
{ power: 18, text: 'Exa', value: 'E' },
{ power: 21, text: 'Zeta', value: 'Z' },
{ power: 24, text: 'Yotta', value: 'Y' }
];
/** @internal */
function findSi(type) {
// use a loop here, better RN support (which doesn't have [].find)
for (let i = 0, count = exports.SI.length; i < count; i++) {
if (exports.SI[i].value === type) {
return exports.SI[i];
}
}
return exports.SI[exports.SI_MID];
}
/** @internal */
function calcSi(text, decimals, forceUnit) {
if (forceUnit) {
return findSi(forceUnit);
}
const siDefIndex = (exports.SI_MID - 1) + Math.ceil((text.length - decimals) / 3);
return exports.SI[siDefIndex] || exports.SI[siDefIndex < 0 ? 0 : exports.SI.length - 1];
}
+14
View File
@@ -0,0 +1,14 @@
/** true if the environment has proper BigInt support */
export declare const hasBigInt: boolean;
/** true if the environment is CJS */
export declare const hasCjs: boolean;
/** true if the environment has __dirname available */
export declare const hasDirname: boolean;
/** true if the environment is ESM */
export declare const hasEsm: boolean;
/** true if the environment has WebAssembly available */
export declare const hasWasm: boolean;
/** true if the environment has support for Buffer (typically Node.js) */
export declare const hasBuffer: boolean;
/** true if the environment has process available (typically Node.js) */
export declare const hasProcess: boolean;
+19
View File
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasProcess = exports.hasBuffer = exports.hasWasm = exports.hasEsm = exports.hasDirname = exports.hasCjs = exports.hasBigInt = void 0;
const x_bigint_1 = require("@pezkuwi/x-bigint");
const x_global_1 = require("@pezkuwi/x-global");
/** true if the environment has proper BigInt support */
exports.hasBigInt = typeof x_bigint_1.BigInt === 'function' && typeof x_bigint_1.BigInt.asIntN === 'function';
/** true if the environment is CJS */
exports.hasCjs = typeof require === 'function' && typeof module !== 'undefined';
/** true if the environment has __dirname available */
exports.hasDirname = typeof __dirname !== 'undefined';
/** true if the environment is ESM */
exports.hasEsm = !exports.hasCjs;
/** true if the environment has WebAssembly available */
exports.hasWasm = typeof WebAssembly !== 'undefined';
/** true if the environment has support for Buffer (typically Node.js) */
exports.hasBuffer = typeof x_global_1.xglobal.Buffer === 'function' && typeof x_global_1.xglobal.Buffer.isBuffer === 'function';
/** true if the environment has process available (typically Node.js) */
exports.hasProcess = typeof x_global_1.xglobal.process === 'object';
+16
View File
@@ -0,0 +1,16 @@
import type { HexString } from '../types.js';
/**
* @name hexAddPrefix
* @summary Adds the `0x` prefix to string values.
* @description
* Returns a `0x` prefixed string from the input value. If the input is already prefixed, it is returned unchanged.
* @example
* <BR>
*
* ```javascript
* import { hexAddPrefix } from '@pezkuwi/util';
*
* console.log('With prefix', hexAddPrefix('0a0b12')); // => 0x0a0b12
* ```
*/
export declare function hexAddPrefix(value?: string | null): HexString;
+23
View File
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hexAddPrefix = hexAddPrefix;
const hasPrefix_js_1 = require("./hasPrefix.js");
/**
* @name hexAddPrefix
* @summary Adds the `0x` prefix to string values.
* @description
* Returns a `0x` prefixed string from the input value. If the input is already prefixed, it is returned unchanged.
* @example
* <BR>
*
* ```javascript
* import { hexAddPrefix } from '@pezkuwi/util';
*
* console.log('With prefix', hexAddPrefix('0a0b12')); // => 0x0a0b12
* ```
*/
function hexAddPrefix(value) {
return value && (0, hasPrefix_js_1.hexHasPrefix)(value)
? value
: `0x${value && value.length % 2 === 1 ? '0' : ''}${value || ''}`;
}

Some files were not shown because too many files have changed in this diff Show More