@winglet/common-utils
v0.15.0
Published
Comprehensive utility library providing commonly used functions for JavaScript/TypeScript projects including array processing, object manipulation, Promise handling, and type checking
Maintainers
Readme
@winglet/common-utils
Overview
@winglet/common-utils is a package that provides various utility functions useful in JavaScript/TypeScript projects.
This library offers commonly used functionalities in various areas including caching, array processing, object manipulation, Promise handling, and type checking.
Installation
# Using npm
npm install @winglet/common-utils
# Using yarn
yarn add @winglet/common-utilsSub-path Imports
This package supports sub-path imports to enable more granular imports and optimize bundle size. You can import specific modules directly without importing the entire package:
// Main exports
import { someUtility } from '@winglet/common-utils';
// Array utilities
import { chunk, intersection, unique } from '@winglet/common-utils/array';
// Console utilities
import { printError } from '@winglet/common-utils/console';
// Constants
import { TIME_UNITS, TYPE_TAGS } from '@winglet/common-utils/constant';
// Convert utilities
import { convertMsFromDuration } from '@winglet/common-utils/convert';
// Error classes
import { AbortError, BaseError } from '@winglet/common-utils/error';
// Filter utilities (type checking)
import {
isArray,
isEmpty,
isFalsy,
isFunction,
isObject,
} from '@winglet/common-utils/filter';
// Function utilities
import { debounce, throttle } from '@winglet/common-utils/function';
// Hash utilities
import { Murmur3 } from '@winglet/common-utils/hash';
// Library utilities
import {
cacheMapFactory,
cacheWeakMapFactory,
} from '@winglet/common-utils/lib';
// Object utilities
import {
clone,
cloneLite,
equals,
merge,
shallowClone,
} from '@winglet/common-utils/object';
// Promise utilities
import { delay, timeout, withTimeout } from '@winglet/common-utils/promise';
// Scheduler utilities
import {
scheduleMacrotask,
scheduleMicrotask,
} from '@winglet/common-utils/scheduler';Available Sub-paths
Based on the package.json exports configuration:
@winglet/common-utils- Main exports (all utilities)@winglet/common-utils/lib- Core library utilities (cache, counter, scheduler)@winglet/common-utils/error- Error classes and utilities (BaseError, AbortError, etc.)@winglet/common-utils/constant- Common constants (time, type tags, units)@winglet/common-utils/filter- Type checking and filtering utilities (isArray, isObject, isFalsy, etc.)@winglet/common-utils/array- Array manipulation utilities (chunk, unique, difference, etc.)@winglet/common-utils/console- Console utilities (printError)@winglet/common-utils/convert- Type conversion utilities (convertMsFromDuration)@winglet/common-utils/function- Function utilities (debounce, throttle, getTrackableHandler)@winglet/common-utils/hash- Hash algorithms (Murmur3)@winglet/common-utils/math- Math utilities (gcd, lcm, abs, minLite, maxLite, clamp, etc.)@winglet/common-utils/object- Object manipulation utilities (clone, cloneLite, merge, equals, etc.)@winglet/common-utils/promise- Promise utilities (delay, timeout, withTimeout, etc.)@winglet/common-utils/scheduler- Task scheduling utilities (scheduleMacrotask, scheduleMicrotask, etc.)
Compatibility
This package is written using ECMAScript 2020 (ES2020) syntax.
Supported Environments:
- Node.js 14.0.0 or higher
- Modern browsers (with ES2020 support)
For Legacy Environment Support: Use transpilers like Babel to convert the code to match your target environment.
Key Features
Constants
- Time-related constants (time.ts)
- Type tag constants (typeTag.ts)
- Unit conversion constants (unit.ts)
- Function constants (function.ts)
Error Handling
BaseError: Base error classAbortError: Error for operation abortionInvalidTypeError: Error for invalid typesTimeoutError: Error for timeouts
Utility Libraries (Libs)
cacheWeakMapFactory: Factory for WeakMap-based cachecacheMapFactory: Factory for Map-based cachecounterFactory: Utility for creating incrementing countersgetKeys: Utility for getting object keysgetTypeTag: Function to get the internal type tag of a JavaScript valuehasOwnProperty: Function to check if an object has a specific propertyrandom: Utilities for random number generation
Utility Functions (Utils)
Array
at: Function to return an element at a specified index in an arraychunk: Function to split an array into chunks of specified sizedifference: Function to return elements in the first array that are not in other arraysdifferenceBy: Function to compute the difference between arrays based on results processed by an iterator functiondifferenceLite: Lightweight version of difference optimized for small arrays (< 100 elements)differenceWith: Function to compute the difference between arrays using a comparator functionforEach: Function to execute a given function for each element in an arrayforEachDual: Function to iterate through two arrays simultaneouslyforEachReverse: Function to execute a function for each element in an array in reverse ordergroupBy: Function to group array elements by the result of an iterator functionintersection: Function to return elements that exist in all arraysintersectionBy: Function to compute the intersection of arrays based on results processed by an iterator functionintersectionLite: Lightweight version of intersection optimized for small arrays (< 100 elements)intersectionWith: Function to compute the intersection of arrays using a comparator functionmap: Function to apply a function to each element in an array and create a new array with the resultsunique: Function to remove duplicate elements from an arrayuniqueBy: Function to return unique elements based on results processed by an iterator functionuniqueWith: Function to return unique elements using a comparator functionprimitiveArrayEqual: Function to compare two arrays for primitive value equality
Console
printError: Function to print error objects to the console in a formatted way
Convert
convertMsFromDuration: Function to convert a single-unit duration string (e.g., '90m', '5s') to milliseconds
DataLoader
DataLoader: Utility class for efficiently loading data by processing requests in batches and caching
Filter
isArray: Function to check if a value is an arrayisArrayBuffer: Function to check if a value is an ArrayBufferisArrayIndex: Function to check if a value is a valid array indexisArrayLike: Function to check if a value is array-likeisBlob: Function to check if a value is a Blob objectisBoolean: Function to check if a value is a BooleanisBuffer: Function to check if a value is a BufferisCloneable: Function to check if a value can be clonedisDataView: Function to check if a value is a DataViewisDate: Function to check if a value is a Date objectisEmptyArray: Function to check if an array is emptyisEmptyObject: Function to check if an object is emptyisEmptyPlainObject: Function to check if a plain object is emptyisEmpty: Function to comprehensively check if a value is empty (null, undefined, empty string, empty array, empty object, etc.)isError: Function to check if a value is an Error objectisFile: Function to check if a value is a File objectisFunction: Function to check if a value is a functionisInteger: Function to check if a value is an integerisMap: Function to check if a value is a Map objectisNil: Function to check if a value is null or undefinedisNotNil: Function to check if a value is not null or undefinedisNull: Function to check if a value is nullisNumber: Function to check if a value is a numberisObject: Function to check if a value is an objectisPlainObject: Function to check if a value is a plain objectisPrimitiveObject: Function to check if a value is a primitive wrapper objectisPrimitiveType: Function to check if a value is a JavaScript primitive typeisPromise: Function to check if a value is a PromiseisRegex: Function to check if a value is a RegExp objectisSet: Function to check if a value is a Set objectisSharedArrayBuffer: Function to check if a value is a SharedArrayBufferisString: Function to check if a value is a stringisSymbol: Function to check if a value is a SymbolisTruthy: Function to check if a value is truthyisFalsy: Function to reliably detect falsy values with TypeScript type guard supportisTypedArray: Function to check if a value is a TypedArrayisUndefined: Function to check if a value is undefinedisValidRegexPattern: Function to check if a string is a valid regex patternisWeakMap: Function to check if a value is a WeakMap objectisWeakSet: Function to check if a value is a WeakSet object
Function
Enhance
getTrackableHandler: Utility to create a wrapper function that can track and manage function execution state
Rate Limit
debounce: Function to delay execution until a certain time has passed with no additional callsthrottle: Function to limit the execution frequency to specified time intervals
Hash
Murmur3: Class implementing the Murmur3 hash algorithm for generating hashes from strings or byte arrayspolynomialHash: Function to convert a string to a base36 hash using a 31-based polynomial rolling hash algorithm
Math
abs: Function to calculate the absolute value of a number with enhanced type safetyclamp: Function to restrict a number to be within a specified rangecombination: Function to calculate the number of combinations (n choose r) using efficient iterative methoddigitSum: Function to calculate the sum of all digits in an integerfactorial: Function to calculate the factorial of a non-negative integer with intelligent cachingfibonacci: Function to calculate the nth Fibonacci number with optimized iterative algorithm and cachingfromBase: Function to convert a string representation of a number in any base (2-36) to decimalgcd: Function to calculate the greatest common divisor (GCD) of two numbers using Euclidean algorithminRange: Function to check if a number falls within a specified range (inclusive)isClose: Function to compare two floating-point numbers for equality within a specified tolerance, handling precision issues across all number magnitudesisEven: Function to determine if a number is even using modulo operationisOdd: Function to determine if a number is odd with proper handling for negative numbersisPrime: Function to determine if a number is prime using optimized trial division algorithmlcm: Function to calculate the least common multiple (LCM) of two numbers with precision handlingmax: Function to find the maximum value in an array of numbers using optimized iterationmaxLite: Function to return the larger of two numbers using simple comparisonmean: Function to calculate the arithmetic mean (average) of an array of numbersmedian: Function to calculate the median (middle value) of an array of numbersmin: Function to find the minimum value in an array of numbers using optimized iterationminLite: Function to return the smaller of two numbers using simple comparisonpermutation: Function to calculate the number of permutations (n permute r) using iterative methodrange: Function to calculate the range (difference between maximum and minimum) of an array of numbersround: Function to round a number to a specified number of decimal placessum: Function to calculate the sum of all numbers in an array using optimized iterationtoBase: Function to convert a decimal integer to its string representation in any base (2-36)
Object
clone: Function to create a deep copy of an objectcloneLite: Function to create high-performance deep clones of simple data structures (primitives, plain objects, and arrays)countKey: Function to count all enumerable properties including inherited onescountObjectKey: Function to count only own enumerable properties of an objectdeleteDataProperty: Function to delete a property with plaindeletesemantics, as the deletion counterpart of the data-property primitivesequals: Function to compare the equality of two objectsgetDataProperty: Function to read a property while treating reserved member names (__proto__,constructor,prototype) as opaque own datagetEmptyObject: Function to create a truly empty object with no prototype chaingetFirstKey: Function to retrieve the first enumerable property key from an objectgetJSONPointer: Function to get a value from an object using a JSON PointergetObjectKeys: Function to return all keys of an object as an arraygetSymbols: Function to return all symbol properties of an object as an arrayhasUndefined: Function to check if an object has undefined valuesisReservedName: Function to check whether a key is a reserved member name that must go through the data-property primitivesmerge: Function to merge multiple objectsremovePrototype: Function to remove the prototype chain from an existing objectremoveUndefined: Function to remove properties with undefined values from an objectsetDataProperty: Function to write a property while treating reserved member names as opaque own data, never triggering the__proto__settershallowClone: Function to create shallow copies of arrays and plain objects, preserving references for nested structuressortObjectKeys: Function to sort an object's keys alphabeticallystableEquals: Function to compare the equality of two objects in a stable waytransformKeys: Function to apply a transformation function to all keys of an objecttransformValues: Function to apply a transformation function to all values of an object
Promise
delay: Function to return a Promise that resolves after waiting for a specified timetimeout: Function to return a Promise that rejects with a timeout error after a specified timewithTimeout: Function to add a timeout to a Promise, causing an error if it doesn't complete within the specified timewaitAndExecute: Function to execute a function after waiting for a specified timewaitAndReturn: Function to return a value after waiting for a specified time
Scheduler
MessageChannelScheduler: Scheduler class that uses MessageChannel to control macro tasks in a fine-grained mannersetImmediate: Function to schedule a macro task using MessageChannelSchedulerclearImmediate: Function to cancel a scheduled macro task using MessageChannelSchedulergetPendingCount: Function to get the number of pending macro tasks using MessageChannelSchedulerdestroyGlobalScheduler: Function to destroy the global MessageChannelScheduler
scheduleMacrotask: Function to schedule a task in the macrotask queuecancelMacrotask: Function to cancel a scheduled macrotaskscheduleCancelableMacrotask: Function to schedule a cancelable macrotaskscheduleMicrotask: Function to schedule a task in the microtask queuescheduleNextTick: Function to schedule a task for the next tick, similar to Node.js's process.nextTick
Usage Examples
Using Cache Utilities
import { cacheMapFactory, cacheWeakMapFactory } from '@winglet/common-utils';
// Create a WeakMap-based cache
const objectCache = cacheWeakMapFactory<string>();
const myObject = { id: 1 };
objectCache.set(myObject, 'cached value');
console.log(objectCache.get(myObject)); // 'cached value'
// Create a Map-based cache
const stringCache = cacheMapFactory<Map<string, number>>();
stringCache.set('key1', 100);
console.log(stringCache.get('key1')); // 100Using Promise Utilities
import { delay, withTimeout } from '@winglet/common-utils';
// Using the delay function
async function delayExample() {
console.log('Start');
await delay(1000); // Wait for 1 second
console.log('After 1 second');
}
// Adding a timeout to an async operation
async function fetchWithTimeout(url: string) {
return withTimeout(() => fetch(url), 5000); // Add a 5-second timeout
}Using Array Utilities
import { array } from '@winglet/common-utils';
// Example code:
const chunks = array.chunk([1, 2, 3, 4, 5, 6], 2);
console.log(chunks); // [[1, 2], [3, 4], [5, 6]]Using Function Tracking Utilities
import { getTrackableHandler } from '@winglet/common-utils';
// Example of tracking async function execution state
const fetchUserData = async (userId: string) => {
const response = await fetch(`/api/users/${userId}`);
return response.json();
};
const trackableFetchUser = getTrackableHandler(fetchUserData, {
preventConcurrent: true, // Prevent concurrent execution
initialState: { loading: false },
beforeExecute: (args, stateManager) => {
stateManager.update({ loading: true });
},
afterExecute: (args, stateManager) => {
stateManager.update({ loading: false });
},
});
// Subscribe to state changes
trackableFetchUser.subscribe(() => {
console.log('Current state:', trackableFetchUser.state);
});
// Execute function
await trackableFetchUser('user123');
console.log('Pending state:', trackableFetchUser.pending); // falseDevelopment Setup
# Clone repository
dir=your-albatrion && git clone https://github.com/vincent-kk/albatrion.git "$dir" && cd "$dir"
# Install dependencies
nvm use && yarn install && yarn run:all build
# Development build
yarn commonUtils build
# Run tests
yarn commonUtils testLicense
This project is licensed under the MIT License. See the **LICENSE file for details.
Contact
For inquiries or suggestions related to the project, please create an issue.
Graph serialization and fingerprints
Use JSON.stringify / JSON.parse for ordinary JSON. Use stringifyGraph /
parseGraph from the package root or /object to preserve cycles, shared
references, Date, Map, Set, BigInt, undefined, special numbers, sparse arrays and
RegExp. The output is JSON syntax, but needs parseGraph to restore the graph.
Functions, symbols, custom classes, binary types and accessors are rejected;
getters and toJSON are never invoked. User non-enumerable properties, descriptors
and frozen state are outside the data model. Recursive omit intentionally
removes named object/array properties before reading them.
Migration (0.16.0)
The serializer APIs deprecated during the 0.15.0 coexistence period are removed in 0.16.0.
| Removed API | Replacement |
| --- | --- |
| serializeNative | JSON.stringify |
| serializeObject | createFingerprint (fast, shallow) |
| serializeWithFullSortedKeys | createSortedFingerprint (flattened paths) |
| stableSerialize | createSafeFingerprint or createFingerprintFactory({ mode: 'safe' }) |
Fingerprint modes have different comparison contracts. Fast mode retains insertion
order and uses native JSON for nested values. Sorted mode flattens sorted paths and
marks cycles; both retain legacy type/delimiter ambiguities and do not compare Map/Set
contents. Safe mode handles cycles and treats Map, Set, functions, symbols and custom
instances by reference identity. Changes inside the same Map/Set do not change its key.
Safe object keys sort by default; { sort: false } skips sorting. Shared and copied
subtrees, or array holes and undefined, may compare equally. These are comparison
keys, not a lossless format, cryptographic hash or fixed-size digest.
Use createFingerprintFactory({ mode: 'fast' | 'sorted' | 'safe' }) to select a
writer once; the default mode is safe. Safe factories also accept sort: false.
Mutable input is recomputed by default; { cache: 'immutable' } requires deeply
immutable input. Recursive omit applies to sorted/safe modes; fast mode omits only
root properties. Ordinary getters may run. Opaque keys are comparable only within
their module/factory identity scope. Invalidate persisted keys when migrating.
Prefixes default to "". Use createFingerprint(value, { prefix: 'app:' })
or createFingerprintFactory({ prefix: 'app:' }) to prepend your own text.
The factory captures its prefix at creation; its generator accepts omit.
Graph v1 limits are 16 MiB UTF-8, 100,000 nodes, 1,000,000 total properties/entries, and 1,000,000 cumulative array slots including holes. Invalid wire is rejected before restored nodes are allocated. Ordinary JSON remains the fastest baseline; graph preservation has additional validation and representation costs.
