UNPKG

@fastkit/helpers

Version:

A small collection of helper implementations for processing primitive values and objects.

473 lines (456 loc) 14.2 kB
export * from '@fastkit/ts-type-utils'; // src/runtime-flags.ts var IN_WINDOW = typeof window !== "undefined"; var IN_DOCUMENT = typeof document !== "undefined"; // src/func.ts function resolveFunctionableValue(source, ...args) { return typeof source === "function" ? source(...args) : source; } resolveFunctionableValue.build = function build(...args) { return (source) => resolveFunctionableValue(source, ...args); }; // src/number.ts function toInt(value) { return typeof value === "number" ? Math.trunc(value) : parseInt(value, 10); } function toFloat(value) { return typeof value === "number" ? value : parseFloat(value); } function toNumber(source) { return typeof source === "number" ? source : Number(source); } // src/delay.ts function delay(milliseconds) { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } // src/promise.ts function isPromise(obj) { return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; } // src/string.ts function isString(source) { return typeof source === "string" || source instanceof String; } function nilToEmptyString(source) { return source == null ? "" : source; } var FULL_WIDTH_SYMBOL_RE = /[!-~]/g; var FULL_WIDTH_SPACE_RE = / /g; var REMOVE_SPACE_RE = /[\s\t]/g; var removeSpace = (source) => nilToEmptyString(source).replace(REMOVE_SPACE_RE, ""); function toHalfWidth(source) { return nilToEmptyString(source).replace( FULL_WIDTH_SYMBOL_RE, (_source) => String.fromCharCode(_source.charCodeAt(0) - 65248) ).replace(FULL_WIDTH_SPACE_RE, " "); } function toSingleSpace(source) { return nilToEmptyString(source).replace(/([\s]+)/g, (m) => m.charAt(0)); } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function uncapitalize(str) { return str.charAt(0).toLowerCase() + str.slice(1); } var INDENT_MATCH_RE = /^[ \t]*(?=\S)/gm; function minIndent(str) { const match = str.match(INDENT_MATCH_RE); if (!match) { return 0; } return match.reduce((r, a) => Math.min(r, a.length), Infinity); } var STRIP_INDENT_UNNECESSARY_LINE_MATCH_RE = /(^\n+|\n\s+$)/g; function stripIndent(str, retainUnnecessaryLines) { if (!retainUnnecessaryLines) { str = str.replace(STRIP_INDENT_UNNECESSARY_LINE_MATCH_RE, ""); } const indent = minIndent(str); if (indent === 0) { return str; } const regex = new RegExp(`^[ \\t]{${indent}}`, "gm"); return str.replace(regex, ""); } // src/set.ts var HAS_SET = typeof Set !== "undefined"; function isSet(source) { return HAS_SET && source instanceof Set; } // src/map.ts var HAS_MAP = typeof Map !== "undefined"; function isMap(source) { return HAS_MAP && source instanceof Map; } // src/regexp.ts function escapeRegExp(str) { return str.replace(/([.*+?^=!:${}()|[\]/\\])/g, "\\$1"); } // src/array.ts function flattenRecursiveArray(source) { const results = []; if (!Array.isArray(source)) { results.push(source); } else { for (const row of source) { results.push(...flattenRecursiveArray(row)); } } return results; } function arrayRemove(array, entry) { const index = array.indexOf(entry); if (index !== -1) { array.splice(index, 1); } } function range(length, offset = 0) { return Array.from(Array(length), (v, k) => k + offset); } function arrayUnique(array) { return Array.from(new Set(array)); } // src/object.ts function inNonNullable(value) { return value != null; } function isNonNullObject(value) { return !!value && typeof value === "object"; } function isObject(value) { return Object.prototype.toString.call(value) === "[object Object]"; } function isPlainObject(value) { if (!isObject(value)) return false; const ctor = value.constructor; if (value.constructor === void 0) return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (prot.hasOwnProperty("isPrototypeOf") === false) { return false; } return true; } function objectIncludes(b, a) { if (a === b) return true; const arrA = Array.isArray(a); const arrB = Array.isArray(b); let i; if (arrA && arrB) { if (a.length != b.length) return false; for (i = 0; i < a.length; i++) if (!objectIncludes(a[i], b[i])) return false; return true; } if (arrA != arrB) return false; if (a && b && typeof a === "object" && typeof b === "object") { const dateA = a instanceof Date; const dateB = b instanceof Date; if (dateA && dateB) return a.getTime() == b.getTime(); if (dateA != dateB) return false; const regexpA = a instanceof RegExp; const regexpB = b instanceof RegExp; if (regexpA && regexpB) return a.toString() == b.toString(); if (regexpA != regexpB) return false; const keys = Object.keys(a); for (i = 0; i < keys.length; i++) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = 0; i < keys.length; i++) if (!objectIncludes(b[keys[i]], a[keys[i]])) return false; return true; } if (a && b && typeof a === "function" && typeof b === "function") { return a.toString() === b.toString(); } return false; } function isIterableObject(source) { return Array.isArray(source) || source && typeof source === "object" && source.constructor.name === "Object" || false; } function isObjectEqual(a = {}, b) { if (!a || !b) return a === b; if (!isObject(b)) return false; const aKeys = Object.keys(a); const bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) { return false; } return aKeys.every((key) => { const aVal = a[key]; const bVal = b[key]; if (aVal == null || bVal == null) return aVal === bVal; if (typeof aVal === "object" && typeof bVal === "object") { return isObjectEqual(aVal, bVal); } return String(aVal) === String(bVal); }); } function objectFromArray(rows, cb) { const entries = new Map(rows.map((row, index) => cb(row, index))); return Object.fromEntries(entries); } objectFromArray.build = (rows) => ( // eslint-disable-next-line no-shadow (cb) => objectFromArray(rows, cb) ); function removeUndef(obj, deep = false) { return Object.keys(obj).reduce((result, key) => { let value = obj[key]; if (value !== void 0) { if (deep && value && typeof value === "object") { value = removeUndef(value, true); } result[key] = value; } return result; }, {}); } function mapFromObjectArray(array, key) { return array.reduce( (prev, current) => { prev[current[key]] = current; return prev; }, {} ); } function pickProperties(obj, props, includesUndefined) { const results = {}; for (const prop of props) { const value = obj[prop]; if (includesUndefined || value !== void 0) { results[prop] = value; } } return results; } function omitProperties(obj, props, excludeUndefined) { const results = { ...obj }; for (const prop of props) { delete results[prop]; } return excludeUndefined ? removeUndef(results) : results; } function mixin(base, trait) { const proxy = new Proxy(base, { get: (_target, propertyKey, receiver) => { const target = Reflect.has(trait, propertyKey) ? trait : _target; return Reflect.get(target, propertyKey, receiver); }, set: (_target, propertyKey, newValue, receiver) => { const target = Reflect.has(trait, propertyKey) ? trait : _target; return Reflect.set(target, propertyKey, newValue, receiver); }, has: (target, propertyKey) => Reflect.has(trait, propertyKey) || Reflect.has(target, propertyKey), ownKeys: (target) => arrayUnique([...Reflect.ownKeys(target), ...Reflect.ownKeys(trait)]), getOwnPropertyDescriptor: (target, propertyKey) => Reflect.getOwnPropertyDescriptor(trait, propertyKey) || Reflect.getOwnPropertyDescriptor(base, propertyKey) }); return proxy; } function mixins(base, ...traits) { const targets = [base, ...traits].reverse(); const proxy = new Proxy(base, { get: (_target, propertyKey, receiver) => { const target = targets.find((t) => Reflect.has(t, propertyKey)) || _target; return Reflect.get(target, propertyKey, receiver); }, set: (_target, propertyKey, newValue, receiver) => { const target = targets.find((t) => Reflect.has(t, propertyKey)) || _target; return Reflect.set(target, propertyKey, newValue, receiver); }, has: (_target, propertyKey) => targets.some((target) => Reflect.has(target, propertyKey)), ownKeys: (_target) => arrayUnique(targets.map((target) => Reflect.ownKeys(target)).flat()), getOwnPropertyDescriptor: (_target, propertyKey) => { for (const target of targets) { const descriptor = Reflect.getOwnPropertyDescriptor( target, propertyKey ); if (descriptor) return descriptor; } } }); return proxy; } // src/object-id.ts var _currentId = 0; var _getNextId = () => { _currentId++; if (_currentId > Number.MAX_SAFE_INTEGER) { _currentId = 1; } return _currentId; }; var _cache = /* @__PURE__ */ new WeakMap(); function temporaryObjectID(obj, onlyClient) { if (onlyClient && !IN_WINDOW) return void 0; let id = _cache.get(obj); if (id === void 0) { id = _getNextId(); _cache.set(obj, id); } return id; } // src/buffer.ts var HAS_BUFFER = typeof Buffer !== "undefined"; var HAS_ARRAY_BUFFER = typeof ArrayBuffer !== "undefined"; function isBuffer(source) { return HAS_BUFFER && source instanceof Buffer; } function isArrayBufferView(source) { return HAS_ARRAY_BUFFER && ArrayBuffer.isView(source); } function copyBuffer(cur) { if (isBuffer(cur)) { return Buffer.from(cur); } return Buffer.from(cur.buffer.slice(0), cur.byteOffset, cur.byteLength); } // src/date.ts function safeGetTimeByDateSource(source) { if (typeof source === "number") return source; if (typeof source === "string") { source = new Date(source); } return source.getTime(); } function toDate(source) { return source instanceof Date ? source : new Date(source); } var DATE_INPUT_PRECISIONS = [ "month", "date", "datetime-local" ]; var DATE_INPUT_PARSE_RE = /^(\d{4})-(\d{2})(-(\d{2})(T(\d{2}):(\d{2}))?)?$/; function parseDateInput(source) { let result = null; const matched = source.match(DATE_INPUT_PARSE_RE); if (matched) { const year = matched[1]; const month = matched[2]; const date = matched[4]; const hours = matched[6]; const minutes = matched[7]; if (hours && minutes) { result = { precision: "datetime-local", year, month, date, hours, minutes, source }; } else if (date) { result = { precision: "date", year, month, date, source }; } else if (year && month) { result = { precision: "month", year, month, source }; } } return result; } // src/general.ts function isEmpty(value) { if (typeof value === "function") return false; return value == null || value === false || value.length === 0; } function notEmptyValue(args, defaultValue) { for (const arg of args) { if (!isEmpty(arg)) { return arg; } } return defaultValue; } // src/defaults.ts var MERGE_DEFAULTS_INDEX_SIGNATURE_SYMBOL = Symbol( "MERGE_DEFAULTS_INDEX_SIGNATURE" ); function getIndexSignatureScheme(scheme) { if (!scheme || Array.isArray(scheme) || typeof scheme !== "object") { return; } const symbols = Object.getOwnPropertySymbols(scheme); if (symbols.some((s) => s === MERGE_DEFAULTS_INDEX_SIGNATURE_SYMBOL)) { return scheme[MERGE_DEFAULTS_INDEX_SIGNATURE_SYMBOL]; } } function createIndexSignatureDefaultsScheme(scheme) { return { [MERGE_DEFAULTS_INDEX_SIGNATURE_SYMBOL]: scheme }; } function mergeDefaults(base, scheme) { const indexSignatureScheme = getIndexSignatureScheme(scheme); if (indexSignatureScheme) { const baseKeys = Object.keys(base); const _scheme = {}; baseKeys.forEach((key) => { _scheme[key] = indexSignatureScheme; }); return mergeDefaults(base, _scheme); } const keys = Object.keys(scheme); for (const key of keys) { const source = scheme[key]; if (!source) { continue; } if (typeof source === "function") { if (base[key] === void 0) { base[key] = source(); } } else if (Array.isArray(source)) { const schemeOrFn = source[0]; if (!base[key] || !Array.isArray(base[key])) { base[key] = []; } const bucket = base[key]; if (typeof schemeOrFn === "function" && !bucket.length) { bucket.push(...schemeOrFn()); } if (typeof schemeOrFn === "object") { const fallbackFn = source[1]; const newItems = []; bucket.forEach((row) => { if (!row || typeof row !== "object") { if (fallbackFn) { row = fallbackFn(row); if (row === void 0) { return; } } else { return; } } newItems.push(mergeDefaults(row, schemeOrFn)); }); base[key] = newItems; } } else { if (!isNonNullObject(base[key])) { base[key] = {}; } base[key] = mergeDefaults(base[key], source); } } return base; } export { DATE_INPUT_PARSE_RE, DATE_INPUT_PRECISIONS, IN_DOCUMENT, IN_WINDOW, MERGE_DEFAULTS_INDEX_SIGNATURE_SYMBOL, arrayRemove, arrayUnique, capitalize, copyBuffer, createIndexSignatureDefaultsScheme, delay, escapeRegExp, flattenRecursiveArray, inNonNullable, isArrayBufferView, isBuffer, isEmpty, isIterableObject, isMap, isNonNullObject, isObject, isObjectEqual, isPlainObject, isPromise, isSet, isString, mapFromObjectArray, mergeDefaults, minIndent, mixin, mixins, nilToEmptyString, notEmptyValue, objectFromArray, objectIncludes, omitProperties, parseDateInput, pickProperties, range, removeSpace, removeUndef, resolveFunctionableValue, safeGetTimeByDateSource, stripIndent, temporaryObjectID, toDate, toFloat, toHalfWidth, toInt, toNumber, toSingleSpace, uncapitalize }; //# sourceMappingURL=helpers.mjs.map //# sourceMappingURL=helpers.mjs.map