UNPKG

@gitborlando/utils

Version:

JavaScript/TypeScript 实用工具集合

373 lines (367 loc) 8.93 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); // src/array.ts function firstOne(input) { if (Array.isArray(input)) return input[0]; return input.values().next().value; } function lastOne(input) { if (Array.isArray(input)) return input[input.length - 1]; const arr = [...input]; return arr[arr.length - 1]; } function flushFuncs(input) { input.forEach((callback) => callback()); Array.isArray(input) ? input.length = 0 : input.clear(); } function stableIndex(arr, index) { if (index === void 0) return arr.length; if (index < 0) return 0; if (index > arr.length) return arr.length; return index; } function loopFor(arr, callback) { for (let index = 0; index < arr.length; index++) { const left = index === 0 ? arr.length - 1 : index - 1; const right = index === arr.length - 1 ? 0 : index + 1; const res = callback(arr[index], arr[right], arr[left], index); if (res === "break") break; if (res === "continue") continue; } } function reverseFor(items, callback) { for (let i = items.length - 1; i >= 0; i--) callback(items[i], i); } function reverse(arr) { return arr.slice().reverse(); } function range(count) { return new Array(count).fill(0).map((_, i) => i); } // src/cache.ts var Cache = class { constructor() { __publicField(this, "cache", /* @__PURE__ */ new Map()); __publicField(this, "compareCache", /* @__PURE__ */ new Map()); } get(key) { return this.cache.get(key); } set(key, value) { this.cache.set(key, value); return value; } delete(key) { this.cache.delete(key); } getSet(key, fn, compare) { const value = this.cache.get(key); if (value === void 0) { return this.set(key, fn()); } if (compare) { const lastCompare = this.compareCache.get(key); const expired = compare?.some((i, index) => i !== lastCompare?.[index]); if (expired) { this.compareCache.set(key, compare); return this.set(key, fn()); } } return value; } clear() { this.cache.clear(); } forEach(callback) { this.cache.forEach((v, k, m) => callback(k, v, m)); } keys() { return this.cache.keys(); } values() { return this.cache.values(); } entries() { return this.cache.entries(); } fromObject(obj) { this.cache = new Map(Object.entries(obj)); } toObject() { return Object.fromEntries( [...this.cache.entries()].map(([key, value]) => [key, value]) ); } }; function createCache() { return new Cache(); } var ObjCache = class { constructor() { __publicField(this, "cache", {}); __publicField(this, "compareCache", /* @__PURE__ */ new Map()); } get(key) { return this.cache[key]; } set(key, value) { this.cache[key] = value; return value; } delete(key) { delete this.cache[key]; } clear() { this.cache = {}; } keys() { return Object.keys(this.cache); } values() { return Object.values(this.cache); } entries() { return Object.entries(this.cache); } getSet(key, fn, compare) { const value = this.cache[key]; if (value === void 0) return this.set(key, fn()); if (!compare) return value; const lastCompare = this.compareCache.get(key); if (compare?.some((i, index) => i !== lastCompare?.[index])) { this.compareCache.set(key, compare); return this.set(key, fn()); } return value; } }; function createObjCache() { return new ObjCache(); } // src/is.ts var Is = class _Is { static number(value) { return typeof value === "number"; } static string(value) { return typeof value === "string"; } static boolean(value) { return typeof value === "boolean"; } static array(value) { return Array.isArray(value); } static object(value) { return typeof value === "object" && value !== null && !_Is.array(value); } static function(value) { return typeof value === "function"; } static null(value) { return value === null; } static undefined(value) { return value === void 0; } static symbol(value) { return typeof value === "symbol"; } static nullable(value) { return value === null || value === void 0; } static notNullable(value) { return value !== null && value !== void 0; } static falsy(value) { return _Is.nullable(value) || value === "null" || value === "undefined" || value === false || value === "false" || value === 0 || value === ""; } static notFalsy(value) { return !_Is.falsy(value); } static empty(value) { if (_Is.array(value)) return value.length === 0; if (_Is.object(value)) return Object.keys(value).length === 0; return _Is.falsy(value); } static notEmpty(value) { return !_Is.empty(value); } }; // src/common.ts var This = globalThis; function Delete(target, filter) { if (Array.isArray(target)) { const index = typeof filter === "function" ? target.findIndex(filter) : target.findIndex((i) => i === filter); index >= 0 && target.splice(index, 1); } else { delete target[filter]; } } function iife(callback) { return callback(); } function matchCase(...args) { if (args.length === 2) { const [Case, obj] = args; return obj[Case]; } else { const [Case, Default, obj] = args; return obj[Case] || Default; } } function Log(someThing, label = "") { console.log(label, someThing); return someThing; } var macroMatchCache = createObjCache(); function macroMatch(_input) { const input = _input[0]; const test = macroMatchCache.getSet(input, () => { const right = input.trimStart().trimEnd().split("|"); return new Function( "left", right.reduce((all, i) => { return `if(left === ${i})return true;` + all; }, "return false;") ); }); return (left) => test(left); } function clone(object) { if (typeof object !== "object" || object === null) return object; const newObj = Array.isArray(object) ? [] : {}; for (const key in object) newObj[key] = clone(object[key]); return newObj; } function jsonFy(obj) { return JSON.stringify(obj, null, 2); } function jsonParse(obj, fallback) { try { return JSON.parse(obj); } catch (e) { console.log("jsonParse error", e); return fallback; } } function memorize(func) { const cache = createObjCache(); return (...args) => { const key = args.join("-"); return cache.getSet(key, () => func(...args)); }; } function debounce(wait, func) { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => func(...args), wait); }; } function objKeys(obj) { return Object.keys(obj); } var Raf = class { constructor() { __publicField(this, "ids", []); } request(callback) { const id = requestAnimationFrame(() => callback(() => this.request(callback))); this.ids.push(id); return this; } cancelAll() { this.ids.forEach(cancelAnimationFrame); return this; } }; var objectKeyMap = /* @__PURE__ */ new WeakMap(); function objectKey(obj) { if (!objectKeyMap.has(obj)) { objectKeyMap.set(obj, miniId()); } return objectKeyMap.get(obj); } function suffixOf(input, lowerCase = false) { if (!input) return ""; const index = input.lastIndexOf("."); if (index === -1) return ""; const suffix = input.slice(index + 1); return lowerCase ? suffix.toLowerCase() : suffix; } function createFuncAOP(before, after) { return (func) => { return (...args) => { before?.(...args); const result = func(...args); after?.(...args); return result; }; }; } function SetTimeout(func, time = 0) { const id = setTimeout(() => { func(); clearTimeout(id); }, time); } function optionalSet(target, key, value) { if (Is.nullable(target)) return; target[key] = value; } function miniId(size = 8, alphabet = "0123456789ABCDEFGHIJKLMNPQRSTUVWXYZ_abcdefghijklmnpqrstuvwxyz") { let id = ""; let i = size | 0; while (i--) { id += alphabet[Math.random() * 61 | 0]; } return id; } function ensure(maybeUndefinedOrNull, fallback) { if (maybeUndefinedOrNull) return maybeUndefinedOrNull; return maybeUndefinedOrNull = fallback; } // src/types.ts function noopFunc() { } function anyFunc(...args) { } var AnyObject = {}; export { AnyObject, Delete, Is, Log, Raf, SetTimeout, This, anyFunc, clone, createCache, createFuncAOP, createObjCache, debounce, ensure, firstOne, flushFuncs, iife, jsonFy, jsonParse, lastOne, loopFor, macroMatch, matchCase, memorize, miniId, noopFunc, objKeys, objectKey, optionalSet, range, reverse, reverseFor, stableIndex, suffixOf };