npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@winglet/common-utils

v0.13.1

Published

Comprehensive utility library providing commonly used functions for JavaScript/TypeScript projects including array processing, object manipulation, Promise handling, and type checking

Downloads

1,512

Readme

@winglet/common-utils

Typescript Javascript


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-utils

Sub-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 {
  mapCacheFactory,
  weakMapCacheFactory,
} 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

Error Handling

Utility Libraries (Libs)

Utility Functions (Utils)

Array

  • at: Function to return an element at a specified index in an array
  • chunk: Function to split an array into chunks of specified size
  • difference: Function to return elements in the first array that are not in other arrays
  • differenceBy: Function to compute the difference between arrays based on results processed by an iterator function
  • differenceLite: Lightweight version of difference optimized for small arrays (< 100 elements)
  • differenceWith: Function to compute the difference between arrays using a comparator function
  • forEach: Function to execute a given function for each element in an array
  • forEachDual: Function to iterate through two arrays simultaneously
  • forEachReverse: Function to execute a function for each element in an array in reverse order
  • groupBy: Function to group array elements by the result of an iterator function
  • intersection: Function to return elements that exist in all arrays
  • intersectionBy: Function to compute the intersection of arrays based on results processed by an iterator function
  • intersectionLite: Lightweight version of intersection optimized for small arrays (< 100 elements)
  • intersectionWith: Function to compute the intersection of arrays using a comparator function
  • map: Function to apply a function to each element in an array and create a new array with the results
  • unique: Function to remove duplicate elements from an array
  • uniqueBy: Function to return unique elements based on results processed by an iterator function
  • uniqueWith: Function to return unique elements using a comparator function
  • primitiveArrayEqual: Function to compare two arrays for primitive value equality

Console

  • printError: Function to print error objects to the console in a formatted way

Convert

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 array
  • isArrayBuffer: Function to check if a value is an ArrayBuffer
  • isArrayIndex: Function to check if a value is a valid array index
  • isArrayLike: Function to check if a value is array-like
  • isBlob: Function to check if a value is a Blob object
  • isBoolean: Function to check if a value is a Boolean
  • isBuffer: Function to check if a value is a Buffer
  • isCloneable: Function to check if a value can be cloned
  • isDataView: Function to check if a value is a DataView
  • isDate: Function to check if a value is a Date object
  • isEmptyArray: Function to check if an array is empty
  • isEmptyObject: Function to check if an object is empty
  • isEmptyPlainObject: Function to check if a plain object is empty
  • isEmpty: 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 object
  • isFile: Function to check if a value is a File object
  • isFunction: Function to check if a value is a function
  • isInteger: Function to check if a value is an integer
  • isMap: Function to check if a value is a Map object
  • isNil: Function to check if a value is null or undefined
  • isNotNil: Function to check if a value is not null or undefined
  • isNull: Function to check if a value is null
  • isNumber: Function to check if a value is a number
  • isObject: Function to check if a value is an object
  • isPlainObject: Function to check if a value is a plain object
  • isPrimitiveObject: Function to check if a value is a primitive wrapper object
  • isPrimitiveType: Function to check if a value is a JavaScript primitive type
  • isPromise: Function to check if a value is a Promise
  • isRegex: Function to check if a value is a RegExp object
  • isSet: Function to check if a value is a Set object
  • isSharedArrayBuffer: Function to check if a value is a SharedArrayBuffer
  • isString: Function to check if a value is a string
  • isSymbol: Function to check if a value is a Symbol
  • isTruthy: Function to check if a value is truthy
  • isFalsy: Function to reliably detect falsy values with TypeScript type guard support
  • isTypedArray: Function to check if a value is a TypedArray
  • isUndefined: Function to check if a value is undefined
  • isValidRegexPattern: Function to check if a string is a valid regex pattern
  • isWeakMap: Function to check if a value is a WeakMap object
  • isWeakSet: 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 calls
  • throttle: 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
  • polynomialHash: 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 safety
  • clamp: Function to restrict a number to be within a specified range
  • combination: Function to calculate the number of combinations (n choose r) using efficient iterative method
  • digitSum: Function to calculate the sum of all digits in an integer
  • factorial: Function to calculate the factorial of a non-negative integer with intelligent caching
  • fibonacci: Function to calculate the nth Fibonacci number with optimized iterative algorithm and caching
  • fromBase: Function to convert a string representation of a number in any base (2-36) to decimal
  • gcd: Function to calculate the greatest common divisor (GCD) of two numbers using Euclidean algorithm
  • inRange: 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 magnitudes
  • isEven: Function to determine if a number is even using modulo operation
  • isOdd: Function to determine if a number is odd with proper handling for negative numbers
  • isPrime: Function to determine if a number is prime using optimized trial division algorithm
  • lcm: Function to calculate the least common multiple (LCM) of two numbers with precision handling
  • max: Function to find the maximum value in an array of numbers using optimized iteration
  • maxLite: Function to return the larger of two numbers using simple comparison
  • mean: Function to calculate the arithmetic mean (average) of an array of numbers
  • median: Function to calculate the median (middle value) of an array of numbers
  • min: Function to find the minimum value in an array of numbers using optimized iteration
  • minLite: Function to return the smaller of two numbers using simple comparison
  • permutation: Function to calculate the number of permutations (n permute r) using iterative method
  • range: Function to calculate the range (difference between maximum and minimum) of an array of numbers
  • round: Function to round a number to a specified number of decimal places
  • sum: Function to calculate the sum of all numbers in an array using optimized iteration
  • toBase: 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 object
  • cloneLite: 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 ones
  • countObjectKey: Function to count only own enumerable properties of an object
  • equals: Function to compare the equality of two objects
  • getEmptyObject: Function to create a truly empty object with no prototype chain
  • getFirstKey: Function to retrieve the first enumerable property key from an object
  • getJSONPointer: Function to get a value from an object using a JSON Pointer
  • getObjectKeys: Function to return all keys of an object as an array
  • getSymbols: Function to return all symbol properties of an object as an array
  • hasUndefined: Function to check if an object has undefined values
  • merge: Function to merge multiple objects
  • removePrototype: Function to remove the prototype chain from an existing object
  • removeUndefined: Function to remove properties with undefined values from an object
  • serializeNative: Function to serialize basic JavaScript objects to JSON strings
  • serializeObject: Function to serialize objects to JSON strings
  • serializeWithFullSortedKeys: Function to serialize objects to JSON strings with sorted keys
  • shallowClone: Function to create shallow copies of arrays and plain objects, preserving references for nested structures
  • sortObjectKeys: Function to sort an object's keys alphabetically
  • stableEquals: Function to compare the equality of two objects in a stable way
  • stableSerialize: Function to serialize objects in a stable way
  • transformKeys: Function to apply a transformation function to all keys of an object
  • transformValues: 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 time
  • timeout: Function to return a Promise that rejects with a timeout error after a specified time
  • withTimeout: Function to add a timeout to a Promise, causing an error if it doesn't complete within the specified time
  • waitAndExecute: Function to execute a function after waiting for a specified time
  • waitAndReturn: Function to return a value after waiting for a specified time

Scheduler


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')); // 100

Using 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]]

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('Loading state:', trackableFetchUser.loading); // false

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 test

License

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.