UNPKG

@w3ux/utils

Version:

A collection of reusable utilities for manipulating data

460 lines (456 loc) 14.3 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { addedTo: () => addedTo, appendOr: () => appendOr, appendOrEmpty: () => appendOrEmpty, applyWidthAsPadding: () => applyWidthAsPadding, camelize: () => camelize, capitalizeFirstLetter: () => capitalizeFirstLetter, ellipsisFn: () => ellipsisFn, eqSet: () => eqSet, extractUrlValue: () => extractUrlValue, formatAccountSs58: () => formatAccountSs58, inChrome: () => inChrome, isSuperset: () => isSuperset, isValidAddress: () => isValidAddress, isValidHttpUrl: () => isValidHttpUrl, localStorageOrDefault: () => localStorageOrDefault, makeCancelable: () => makeCancelable, matchedProperties: () => matchedProperties, maxBigInt: () => maxBigInt, mergeDeep: () => mergeDeep, minBigInt: () => minBigInt, minDecimalPlaces: () => minDecimalPlaces, pageFromUri: () => pageFromUri, planckToUnit: () => planckToUnit, remToUnit: () => remToUnit, removeHexPrefix: () => removeHexPrefix, removeVarFromUrlHash: () => removeVarFromUrlHash, removedFrom: () => removedFrom, rmCommas: () => rmCommas, rmDecimals: () => rmDecimals, setStateWithRef: () => setStateWithRef, shuffle: () => shuffle, snakeToCamel: () => snakeToCamel, sortWithNull: () => sortWithNull, u8aConcat: () => u8aConcat, unescape: () => unescape, unimplemented: () => unimplemented, unitToPlanck: () => unitToPlanck, varToUrlHash: () => varToUrlHash, withTimeout: () => withTimeout, withTimeoutThrow: () => withTimeoutThrow }); module.exports = __toCommonJS(index_exports); // src/base.ts var import_utils = require("dedot/utils"); var minDecimalPlaces = (val, minDecimals) => { try { const retainCommas = typeof val === "string" && val.includes(","); const strVal = typeof val === "string" ? val.replace(/,/g, "") : val.toString(); const [integerPart, fractionalPart = ""] = strVal.split("."); const whole = BigInt(integerPart || "0"); const missingDecimals = minDecimals - fractionalPart.length; const formattedWhole = retainCommas ? Intl.NumberFormat("en-US").format(whole) : whole.toString(); return missingDecimals > 0 ? `${formattedWhole}.${fractionalPart}${"0".repeat(missingDecimals)}` : `${formattedWhole}.${fractionalPart}`; } catch (e) { return "0"; } }; var camelize = (str) => { const convertToString = (string) => { if (string) { if (typeof string === "string") { return string; } return String(string); } return ""; }; const toWords = (inp) => convertToString(inp).match( /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g ); const simpleCamelCase = (inp) => { let result = ""; for (let i = 0; i < inp?.length; i++) { const currString = inp[i]; let tmpStr = currString.toLowerCase(); if (i != 0) { tmpStr = tmpStr.slice(0, 1).toUpperCase() + tmpStr.slice(1, tmpStr.length); } result += tmpStr; } return result; }; const w = toWords(str)?.map((a) => a.toLowerCase()); return simpleCamelCase(w || []); }; var ellipsisFn = (str, amount = 6, position = "center") => { const half = str.length / 2; if (amount <= 4) { if (position === "center") { return str.slice(0, 4) + "..." + str.slice(-4); } if (position === "end") { return str.slice(0, 4) + "..."; } return "..." + str.slice(-4); } if (position === "center") { return amount >= (str.length - 2) / 2 ? str.slice(0, half - 3) + "..." + str.slice(-(half - 3)) : str.slice(0, amount) + "..." + str.slice(-amount); } if (amount >= str.length) { if (position === "end") { return str.slice(0, str.length - 3) + "..."; } return "..." + str.slice(-(str.length - 3)); } else { if (position === "end") { return str.slice(0, amount) + "..."; } return "..." + str.slice(amount); } }; var pageFromUri = (pathname, fallback) => { const lastUriItem = pathname.substring(pathname.lastIndexOf("/") + 1); const page = lastUriItem.trim() === "" ? fallback : lastUriItem; return page.trim(); }; var rmCommas = (val) => val.replace(/,/g, ""); var rmDecimals = (str) => str.split(".")[0]; var shuffle = (array) => { let currentIndex = array.length; let randomIndex; while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex] ]; } return array; }; var withTimeout = (ms, promise, options) => { const timeout = new Promise( (resolve) => setTimeout(async () => { if (typeof options?.onTimeout === "function") { options.onTimeout(); } resolve(void 0); }, ms) ); return Promise.race([promise, timeout]); }; var withTimeoutThrow = (ms, promise, options) => { const timeout = new Promise( (reject) => setTimeout(async () => { if (typeof options?.onTimeout === "function") { options.onTimeout(); } reject("Function timeout"); }, ms) ); return Promise.race([promise, timeout]); }; var appendOrEmpty = (condition, value) => condition ? ` ${value}` : ""; var appendOr = (condition, value, fallback) => condition ? ` ${value}` : ` ${fallback}`; var formatAccountSs58 = (address, ss58Prefix) => { try { return (0, import_utils.encodeAddress)(address, ss58Prefix); } catch (e) { return null; } }; var removeHexPrefix = (str) => str.replace(/^0x/, ""); var eqSet = (xs, ys) => xs.size === ys.size && [...xs].every((x) => ys.has(x)); var isSuperset = (set, subset) => { for (const elem of subset) { if (!set.has(elem)) { return false; } } return true; }; var maxBigInt = (...values) => values.reduce((max, current) => current > max ? current : max); var minBigInt = (...values) => values.reduce((min, current) => current < min ? current : min); // src/convert.ts var u8aConcat = (...u8as) => { const totalLength = u8as.reduce((sum, u8a) => sum + u8a.length, 0); const result = new Uint8Array(totalLength); let offset = 0; for (const u8a of u8as) { result.set(u8a, offset); offset += u8a.length; } return result; }; // src/unit.ts var import_utils2 = require("dedot/utils"); var planckToUnit = (val, units) => { try { units = Math.max(Math.round(units), 0); const bigIntVal = typeof val === "bigint" ? val : BigInt( typeof val === "number" ? Math.floor(val).toString() : rmDecimals(rmCommas(val)) ); const divisor = units === 0 ? 1n : BigInt(10) ** BigInt(units); const integerPart = bigIntVal / divisor; const fractionalPart = bigIntVal % divisor; const fractionalStr = units > 0 ? `.${fractionalPart.toString().padStart(units, "0")}` : ``; return `${integerPart}${fractionalStr}`; } catch (e) { return "0"; } }; var unitToPlanck = (val, units) => { try { units = Math.max(Math.round(units), 0); const strVal = (typeof val === "string" ? rmCommas(val) : val.toString()) || "0"; const [integerPart, fractionalPart = ""] = strVal.split("."); let bigIntValue = BigInt(integerPart) * BigInt(10) ** BigInt(units); if (fractionalPart) { let fractionalValue; if (fractionalPart.length > units) { fractionalValue = BigInt(fractionalPart.slice(0, units)); } else { fractionalValue = BigInt(fractionalPart.padEnd(units, "0")); } bigIntValue += fractionalValue; } return bigIntValue; } catch (e) { return BigInt(0); } }; var remToUnit = (rem) => Number(rem.slice(0, rem.length - 3)) * parseFloat(getComputedStyle(document.documentElement).fontSize); var capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1); var snakeToCamel = (str) => str.toLowerCase().replace( /([-_][a-z])/g, (group) => group.toUpperCase().replace("-", "").replace("_", "") ); var setStateWithRef = (value, setState, ref) => { setState(value); ref.current = value; }; var localStorageOrDefault = (key, _default, parse = false) => { const val = localStorage.getItem(key); if (val === null) { return _default; } if (parse) { return JSON.parse(val); } return val; }; var isValidAddress = (address) => { try { (0, import_utils2.decodeAddress)(address); return true; } catch (e) { return false; } }; var extractUrlValue = (key, url) => { if (typeof url === "undefined") { url = window.location.href; } const match = url.match(`[?&]${key}=([^&]+)`); return match ? match[1] : null; }; var varToUrlHash = (key, val, addIfMissing) => { const hash = window.location.hash; const [page, params] = hash.split("?"); const searchParams = new URLSearchParams(params); if (searchParams.get(key) === null && !addIfMissing) { return; } searchParams.set(key, val); window.location.hash = `${page}?${searchParams.toString()}`; }; var removeVarFromUrlHash = (key) => { const hash = window.location.hash; const [page, params] = hash.split("?"); const searchParams = new URLSearchParams(params); if (searchParams.get(key) === null) { return; } searchParams.delete(key); const paramsAsStr = searchParams.toString(); window.location.hash = `${page}${paramsAsStr ? `?${paramsAsStr}` : ``}`; }; var sortWithNull = (ascending) => (a, b) => { if (typeof a === "undefined" && typeof b === "undefined") { return 0; } if (typeof a === "undefined" || typeof b === "undefined") { return typeof a === "undefined" ? 1 : -1; } if (a === b) { return 0; } if (a === null) { return 1; } if (b === null) { return -1; } if (ascending) { return a < b ? -1 : 1; } return a < b ? 1 : -1; }; var applyWidthAsPadding = (subjectRef, containerRef) => { if (containerRef.current && subjectRef.current) { containerRef.current.style.paddingRight = `${subjectRef.current.offsetWidth + remToUnit("1rem")}px`; } }; var unescape = (val) => val.replace(/\\"/g, '"'); var inChrome = () => { const isChromium = window?.chrome || null; const winNav = window?.navigator || null; const isOpera = typeof window?.opr !== "undefined"; const isIEedge = winNav?.userAgent.indexOf("Edg") > -1 || false; const isIOSChrome = winNav?.userAgent.match("CriOS") || false; if (isIOSChrome) { return true; } if (isChromium !== null && typeof isChromium !== "undefined" && isOpera === false && isIEedge === false) { return true; } return false; }; var addedTo = (fresh, stale, keys) => typeof fresh !== "object" || typeof stale !== "object" || !keys.length ? [] : fresh.filter( (freshItem) => !stale.find( (staleItem) => keys.every( (key) => !(key in staleItem) || !(key in freshItem) ? false : staleItem[key] === freshItem[key] ) ) ); var removedFrom = (fresh, stale, keys) => typeof fresh !== "object" || typeof stale !== "object" || !keys.length ? [] : stale.filter( (staleItem) => !fresh.find( (freshItem) => keys.every( (key) => !(key in staleItem) || !(key in freshItem) ? false : freshItem[key] === staleItem[key] ) ) ); var matchedProperties = (objX, objY, keys) => typeof objX !== "object" || typeof objY !== "object" || !keys.length ? [] : objY.filter( (x) => objX.find( (y) => keys.every( (key) => !(key in x) || !(key in y) ? false : y[key] === x[key] ) ) ); var isValidHttpUrl = (string) => { let url; try { url = new URL(string); } catch (_) { return false; } return url.protocol === "http:" || url.protocol === "https:"; }; var makeCancelable = (promise) => { let hasCanceled = false; const wrappedPromise = new Promise((resolve, reject) => { promise.then( (val) => hasCanceled ? reject(Error("Cancelled")) : resolve(val) ); promise.catch( (error) => hasCanceled ? reject(Error("Cancelled")) : reject(error) ); }); return { promise: wrappedPromise, cancel: () => { hasCanceled = true; } }; }; var unimplemented = ({ ...props }) => { }; var mergeDeep = (target, ...sources) => { if (!sources.length) { return target; } const isObject = (item) => item && typeof item === "object" && !Array.isArray(item); const source = sources.shift(); if (isObject(target) && isObject(source)) { for (const key in source) { if (isObject(source[key])) { if (!target[key]) { Object.assign(target, { [key]: {} }); } mergeDeep(target[key], source[key]); } else { Object.assign(target, { [key]: source[key] }); } } } return mergeDeep(target, ...sources); }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { addedTo, appendOr, appendOrEmpty, applyWidthAsPadding, camelize, capitalizeFirstLetter, ellipsisFn, eqSet, extractUrlValue, formatAccountSs58, inChrome, isSuperset, isValidAddress, isValidHttpUrl, localStorageOrDefault, makeCancelable, matchedProperties, maxBigInt, mergeDeep, minBigInt, minDecimalPlaces, pageFromUri, planckToUnit, remToUnit, removeHexPrefix, removeVarFromUrlHash, removedFrom, rmCommas, rmDecimals, setStateWithRef, shuffle, snakeToCamel, sortWithNull, u8aConcat, unescape, unimplemented, unitToPlanck, varToUrlHash, withTimeout, withTimeoutThrow }); /* @license Copyright 2024 w3ux authors & contributors SPDX-License-Identifier: GPL-3.0-only */ // /* @license Copyright 2024 w3ux authors & contributors //# sourceMappingURL=index.cjs.map