UNPKG

@corentinth/chisels

Version:

Collection of utilities for JavaScript and TypeScript, lightweight and tree-shakable.

84 lines (77 loc) 2.16 kB
const unitsByBase = { 1e3: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], 1024: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] }; function formatBytes({ bytes, decimals = 2, base = 1024, units = unitsByBase[base] }) { if (units === void 0 || units.length === 0) { throw new Error(`No units defined for base ${base}`); } if (bytes === 0) { return `0 ${units[0]}`; } const exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(base)), units.length - 1); const value = bytes / base ** exponent; return `${value.toFixed(decimals)} ${units[exponent]}`; } function castError(error) { return error instanceof Error ? error : new Error(error ? String(error) : void 0); } function injectArguments(functions, injectedArgs) { return Object.fromEntries(Object.entries(functions).map(([key, fn]) => [key, (args) => fn({ ...args, ...injectedArgs })])); } function memoizeOnce(value) { let isCalled = false; let cache; return () => { if (!isCalled) { isCalled = true; cache = value(); } return cache; }; } async function safely(fn) { try { const result = typeof fn === "function" ? await fn() : await fn; return [result, null]; } catch (error) { return [null, castError(error)]; } } function safelySync(fn) { try { return [fn(), null]; } catch (error) { return [null, castError(error)]; } } function joinUrlPaths(...parts) { return parts.map((part) => part?.replace(/(^\/|\/$)/g, "")).filter(Boolean).join("/"); } function buildUrl({ path: pathOrPaths = "", baseUrl, queryParams, hash }) { const path = Array.isArray(pathOrPaths) ? joinUrlPaths(...pathOrPaths) : pathOrPaths; const url = new URL(path, baseUrl); if (queryParams) { if (queryParams instanceof URLSearchParams) { url.search = queryParams.toString(); } else { url.search = new URLSearchParams(queryParams).toString(); } } if (hash) { url.hash = hash; } return url.toString(); } export { buildUrl, castError, formatBytes, injectArguments, joinUrlPaths, memoizeOnce, safely, safelySync }; //# sourceMappingURL=index.mjs.map