UNPKG

@w3ux/utils

Version:

A collection of reusable utilities for manipulating data

260 lines (253 loc) 10.6 kB
import { RefObject, ForwardedRef } from 'react'; /** * Ensures a number has at least the specified number of decimal places, retaining commas in the output if they are present in the input. * * @function minDecimalPlaces * @param {string | number | BigInt} val - The input number, which can be a `string` with or without commas, a `number`, or a `BigInt`. * @param {number} minDecimals - The minimum number of decimal places to enforce. * @returns {string} The formatted number as a string, padded with zeros if needed to meet `minDecimals`, retaining commas if originally provided. * If `val` is invalid, returns "0". * @example * // Pads "1,234.5" to have at least 3 decimal places, with commas * minDecimalPlaces("1,234.5", 3); // returns "1,234.500" * * // Returns "1234.56" unchanged * minDecimalPlaces(1234.56, 2); // returns "1234.56" * * // Pads BigInt 1234 with 2 decimals * minDecimalPlaces(BigInt(1234), 2); // returns "1234.00" */ declare const minDecimalPlaces: (val: string | number | bigint, minDecimals: number) => string; /** * @name camelize * @summary Converts a string of text to camelCase. */ declare const camelize: (str: string) => string; /** * @name ellipsisFn * @summary Receives an address and creates ellipsis on the given string, based on parameters. * @param str - The string to apply the ellipsis on * @param amount - The amount of characters that the ellipsis will be * @param position - where the ellipsis will apply; if center the amount of character is the * same for beginning and end; if "start" or "end" then its only once the amount; defaults to "start" */ declare const ellipsisFn: (str: string, amount?: number, position?: "start" | "end" | "center") => string; /** * @name pageFromUri * @summary Use url variables to load the default components upon the first page visit. */ declare const pageFromUri: (pathname: string, fallback: string) => string; /** * @name rmCommas * @summary Removes the commas from a string. */ declare const rmCommas: (val: string) => string; /** * @name rmDecimals * @summary Removes the decimal point and decimals from a string. */ declare const rmDecimals: (str: string) => string; /** * @name shuffle * @summary Shuffle a set of objects. */ declare const shuffle: <T>(array: T[]) => T[]; /** * @name withTimeout * @summary Timeout a promise after a specified number of milliseconds. */ declare const withTimeout: (ms: number, promise: Promise<unknown>, options?: { onTimeout?: () => void; }) => Promise<unknown>; /** * @name withTimeoutThrow * @summary Timeout a promise after a specified number of milliseconds by throwing an error */ declare const withTimeoutThrow: <T>(ms: number, promise: Promise<T>, options?: { onTimeout?: () => void; }) => Promise<unknown>; /** * @name appendOrEmpty * @summary Returns ` value` if a condition is truthy, or an empty string otherwise. */ declare const appendOrEmpty: (condition: boolean | string | undefined, value: string) => string; /** * @name appendOr * @summary Returns ` value` if condition is truthy, or ` fallback` otherwise. */ declare const appendOr: (condition: boolean | string | undefined, value: string, fallback: string) => string; /** * @name removeHexPrefix * @summary Takes a string str as input and returns a new string with the "0x" prefix removed if it * exists at the beginning of the input string. */ declare const removeHexPrefix: (str: string) => string; declare const eqSet: (xs: Set<any>, ys: Set<any>) => boolean; declare const isSuperset: (set: Set<any>, subset: Set<any>) => boolean; /** * Finds the maximum value among a list of BigInt values. * * @function maxBigInt * @param {...bigint} values - A list of BigInt values to compare. * @returns {bigint} The largest BigInt value in the provided list. * @example * // Returns the maximum BigInt value * maxBigInt(10n, 50n, 30n, 100n, 20n); // 100n */ declare const maxBigInt: (...values: bigint[]) => bigint; /** * Finds the minimum value among a list of BigInt values. * * @function minBigInt * @param {...bigint} values - A list of BigInt values to compare. * @returns {bigint} The smallest BigInt value in the provided list. * @example * // Returns the minimum BigInt value * minBigInt(10n, 50n, 30n, 100n, 20n); // 10n */ declare const minBigInt: (...values: bigint[]) => bigint; /** * Concatenates multiple Uint8Array instances into a single Uint8Array. * * @param {Uint8Array[]} u8as - An array of Uint8Array instances to concatenate. * @returns {Uint8Array} A new Uint8Array containing all the input arrays concatenated. */ declare const u8aConcat: (...u8as: Uint8Array[]) => Uint8Array; declare const mergeRefs: <T extends HTMLElement>(el: T | null, internalRef: RefObject<HTMLElement | null>, externalRef: ForwardedRef<T>) => void; type AnyObject = any; /** * Converts an on-chain balance value from planck to a decimal value in token units. * * @function planckToUnit * @param {number | BigInt | string} val - The balance value in planck. Accepts a `number`, `BigInt`, or `string`. * @param {number} units - The number of decimal places in the token unit (10^units planck per 1 token). * @returns {string} The equivalent token unit value as a decimal string. * @example * // Convert 1500000000000 planck to tokens with 12 decimal places * planckToUnit("1500000000000", 12); // returns "1.5" */ declare const planckToUnit: (val: number | bigint | string, units: number) => string; /** * Converts a token unit value to an integer value in planck. * * @function unitToPlanck * @param {string | number | BigInt} val - The token unit value to convert. Accepts a string, number, or BigInt. * @param {number} units - The number of decimal places for conversion (10^units planck per 1 token). * @returns {BigInt} The equivalent value in planck as a BigInt. * @example * // Convert "1.5" tokens to planck with 12 decimal places * unitToPlanck("1.5", 12); // returns BigInt("1500000000000") */ declare const unitToPlanck: (val: string | number | bigint, units: number) => bigint; /** * @name remToUnit * @summary Converts a rem string to a number. */ declare const remToUnit: (rem: string) => number; /** * @name capitalizeFirstLetter * @summary Capitalize the first letter of a string. */ declare const capitalizeFirstLetter: (string: string) => string; /** * @name snakeToCamel * @summary converts a string from snake / kebab-case to camel-case. */ declare const snakeToCamel: (str: string) => string; /** * @name setStateWithRef * @summary Synchronize React state and its reference with the provided value. */ declare const setStateWithRef: <T>(value: T, setState: (_state: T) => void, ref: RefObject<T>) => void; /** * @name localStorageOrDefault * @summary Retrieve the local stroage value with the key, return defult value if it is not * found. */ declare const localStorageOrDefault: <T>(key: string, _default: T, parse?: boolean) => T | string; /** * @name extractUrlValue * @summary Extracts a URL value from a URL string. */ declare const extractUrlValue: (key: string, url?: string) => string | null; /** * @name varToUrlHash * @summary Puts a variable into the URL hash as a param. * @description * Since url variables are added to the hash and are not treated as URL params, the params are split * and parsed into a `URLSearchParams`. */ declare const varToUrlHash: (key: string, val: string, addIfMissing: boolean) => void; /** * @name removeVarFromUrlHash * @summary * Removes a variable `key` from the URL hash if it exists. Removes dangling `?` if no URL variables * exist. */ declare const removeVarFromUrlHash: (key: string) => void; /** * @name sortWithNull * @summary Sorts an array with nulls last. */ declare const sortWithNull: (ascending: boolean) => (a: unknown, b: unknown) => 0 | 1 | -1; /** * @name applyWidthAsPadding * @summary Applies width of subject to paddingRight of container. */ declare const applyWidthAsPadding: (subjectRef: RefObject<HTMLDivElement | null>, containerRef: RefObject<HTMLDivElement | null>) => void; /** * @name unescape * @summary Replaces \” with “ */ declare const unescape: (val: string) => string; /** * @name inChrome * @summary Whether the application is rendering in Chrome. */ declare const inChrome: () => boolean; /** * @name addedTo * @summary Given 2 objects and some keys, return items in the fresh object that do not exist in the * stale object by matching the given common key values of both objects. */ declare const addedTo: (fresh: AnyObject[], stale: AnyObject[], keys: string[]) => AnyObject[]; /** * @name removedFrom * @summary Given 2 objects and some keys, return items in the stale object that do not exist in the * fresh object by matching the given common key values of both objects. */ declare const removedFrom: (fresh: AnyObject[], stale: AnyObject[], keys: string[]) => AnyObject[]; /** * @name matchedProperties * @summary Given 2 objects and some keys, return items in object 1 that also exist in object 2 by * matching the given common key values of both objects. */ declare const matchedProperties: (objX: AnyObject[], objY: AnyObject[], keys: string[]) => AnyObject[]; /** * @name isValidHttpUrl * @summary Give a string, return whether it is a valid http URL. * @param string - The string to check. */ declare const isValidHttpUrl: (string: string) => boolean; /** * @name makeCancelable * @summary Makes a promise cancellable. * @param promise - The promise to make cancellable. */ declare const makeCancelable: (promise: Promise<AnyObject>) => { promise: Promise<unknown>; cancel: () => void; }; /** * @name unimplemented * @summary A placeholder function to signal a deliberate unimplementation. * Consumes an arbitrary number of props. */ declare const unimplemented: (_props?: unknown) => void; /** * Deep merge two objects. * @param target * @param ...sources */ declare const mergeDeep: (target: AnyObject, ...sources: AnyObject[]) => AnyObject; export { addedTo, appendOr, appendOrEmpty, applyWidthAsPadding, camelize, capitalizeFirstLetter, ellipsisFn, eqSet, extractUrlValue, inChrome, isSuperset, isValidHttpUrl, localStorageOrDefault, makeCancelable, matchedProperties, maxBigInt, mergeDeep, mergeRefs, minBigInt, minDecimalPlaces, pageFromUri, planckToUnit, remToUnit, removeHexPrefix, removeVarFromUrlHash, removedFrom, rmCommas, rmDecimals, setStateWithRef, shuffle, snakeToCamel, sortWithNull, u8aConcat, unescape, unimplemented, unitToPlanck, varToUrlHash, withTimeout, withTimeoutThrow };