UNPKG

tsid-ts

Version:

A TypeScript library for generating Time-Sorted Unique Identifiers (TSID).

52 lines (51 loc) 1.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.uniformInt = exports.decode = exports.encode = void 0; // Base 62 var ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; /** * Encodes a bigint value into a string representation using the specified base. * @param value - The bigint value to encode. * @param base - The base to use for encoding. * @param minLength - The minimum length of the encoded string. Optional. * @returns The encoded string. */ function encode(value, base, minLength) { var result = []; while (value > 0) { result.push(ALPHABET[Number(value % BigInt(base))]); value = BigInt(Math.floor(Number(value / BigInt(base)))); } if (minLength && result.length < minLength) { result.push.apply(result, Array(minLength - result.length).fill('0')); } return result.reverse().join(''); } exports.encode = encode; /** * Decodes a string value into a number using the specified base. * @param value The string value to decode. * @param base The base to use for decoding. * @returns The decoded number. */ function decode(value, base) { var result = 0; for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { var c = value_1[_i]; result *= base; result += ALPHABET.indexOf(c); } return result; } exports.decode = decode; /** * Generates a random integer between min (inclusive) and max (inclusive). * * @param {number} min - The minimum value of the range. * @param {number} max - The maximum value of the range. * @returns {number} A random integer between min and max (inclusive). */ function uniformInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } exports.uniformInt = uniformInt;