Package Exports
- @winglet/common-utils
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-utilsKey Features
Constants
- Time-related constants (time.ts)
- Type tag constants (typeTag.ts)
- Unit conversion constants (unit.ts)
Error Handling
BaseError: Base error classAbortError: Error for operation abortionInvalidTypeError: Error for invalid typesTimeoutError: Error for timeouts
Utility Libraries (Libs)
weakMapCacheFactory: Factory for WeakMap-based cachemapCacheFactory: Factory for Map-based cachecounter: 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 functiondifferenceWith: 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 functionintersectionWith: 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 function
Console
printError: Function to print error objects to the console in a formatted way
Convert
convertMsFromDuration: Function to convert a duration string (e.g., '1h30m') 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 emptyisError: 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 truthyisTypedArray: 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
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 arrays
JSON
JSONPath: An expression system for querying and manipulating specific values within JSON data.JSONPointer: An implementation of JSON Pointer as defined in RFC 6901, used to reference specific locations within a JSON document.getValueByPointer: Retrieves a value from JSON data based on a JSON Pointer.setValueByPointer: Sets a value in JSON data based on a JSON Pointer.escapePointer: Escapes a JSON Pointer string.unescapePointer: Unescapes a JSON Pointer string.
Object
clone: Function to create a deep copy of an objectequals: Function to compare the equality of two objectsgetJSONPointer: 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 valuesmerge: Function to merge multiple objectsremoveUndefined: Function to remove properties with undefined values from an objectserializeNative: Function to serialize basic JavaScript objects to JSON stringsserializeObject: Function to serialize objects to JSON stringsserializeWithFullSortedKeys: Function to serialize objects to JSON strings with sorted keyssortObjectKeys: Function to sort an object's keys alphabeticallystableEquals: Function to compare the equality of two objects in a stable waystableSerialize: Function to serialize 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
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 { mapCacheFactory, weakMapCacheFactory } from '@winglet/common-utils';
// Create a WeakMap-based cache
const objectCache = weakMapCacheFactory<string>();
const myObject = { id: 1 };
objectCache.set(myObject, 'cached value');
console.log(objectCache.get(myObject)); // 'cached value'
// Create a Map-based cache
const stringCache = mapCacheFactory<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 a Promise
async function fetchWithTimeout(url: string) {
const fetchPromise = fetch(url);
return withTimeout(fetchPromise, 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]]Development 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.