Skip to content

Comprehensive TypeScript/JavaScript utility library with cross-environment support (Node.js, browser, web worker) providing helper functions, polyfills (ES5-ES2023), type checking utilities, and optimized implementations for better minification and code readability.

License

Notifications You must be signed in to change notification settings

nevware21/ts-utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@nevware21/ts-utils

Comprehensive TypeScript/JavaScript Utility Library

GitHub Workflow Status (main) codecov npm version downloads downloads Sponsor

Overview

A comprehensive TypeScript/JavaScript utility library that provides:

  • Cross-Environment Support: Works seamlessly in Node.js, browsers, and web workers
  • Helper Functions: Extensive collection of utility functions for common operations
  • Type Checking: Robust type checking utilities to improve code reliability
  • Optimized for Minification: Function naming designed for better minification
  • Zero Dependencies: Lightweight and self-contained
  • ECMAScript Support: Supports modern JavaScript features across ES5 to ES2023, ensuring broad usability in various environments
  • Polyfills: Uses built-in functions to support older environments, providing modern JavaScript features without sacrificing compatibility

If you find this library useful, please consider sponsoring @nevware21 to support ongoing development and maintenance.

Installation

npm install @nevware21/ts-utils --save

Recommended Version Specification:

"@nevware21/ts-utils": ">= 0.12.4 < 2.x"

Note: v0.x and v1.x maintain ES5 compatibility. Future v2.x releases will update the baseline to newer ECMAScript versions.

Key Features

Environment Utilities

  • Global object detection and access
  • Environment detection (Node.js, browser, web worker)
  • Safe access to environment-specific APIs

Type Checking

  • Comprehensive type checking for all JavaScript types
  • Value validation helpers
  • Advanced type checks for promises, iterables, and more

Array Helpers

  • Safe array manipulation with polyfills for older environments
  • Cross-environment array utilities
  • Performance-optimized implementations

Object Utilities

  • Property manipulation
  • Deep copy/extend
  • Object transformation helpers

String Manipulation

  • Case conversion (camelCase, kebab-case, snake_case)
  • String transformation utilities
  • HTML and JSON encoding

Function Helpers

  • Function binding and proxying utilities
  • Argument manipulation
  • Function creation helpers

Time and Performance

  • Consistent timing APIs across environments
  • Performance measurement utilities
  • Scheduling helpers with automatic polyfills
  • Customizable timeout handling via package-level and global overrides

For advanced timeout customization options, including global overrides, see our Timeout Overrides Guide.

And More

  • Math utilities
  • Symbol polyfills
  • RegExp helpers
  • Iterator utilities

Documentation & API Reference

Visit our documentation site for comprehensive guides and references.

Documentation Quick Links

Category Documentation
Getting Started Usage Guide
Advanced Features Timeout Overrides, Deep Copy
Performance Bundle Size Optimization
API Reference TypeDoc Documentation

Available Utilities

Below is a categorized list of all available utilities with direct links to their documentation:

Type Functions / Helpers / Aliases / Polyfills
Runtime Environment Checks getCancelIdleCallback(); getDocument(); getGlobal(); getHistory(); getIdleCallback(); getInst(); getNavigator(); getPerformance(); getWindow(); hasDocument(); hasHistory(); hasNavigator(); hasPerformance(); hasWindow(); isNode(); isWebWorker(); hasIdleCallback(); lazySafeGetInst();
Type Identity isArray(); isArrayBuffer(); isAsyncFunction(); isAsyncGenerator(); isBigInt(); isBlob(); isBoolean(); isDate(); isElement(); isElementLike(); isError(); isFile(); isFiniteNumber(); isFormData(); isFunction(); isGenerator(); isInteger(); isIterable(); isIterator(); isMap(); isMapLike(); isNullOrUndefined(); isNumber(); isObject(); isPlainObject(); isPrimitive(); isPrimitiveType(); isPromise(); isPromiseLike(); isRegExp(); isSet(); isSetLike(); isStrictNullOrUndefined(); isStrictUndefined(); isString(); isThenable(); isTypeof(); isUndefined(); isWeakMap(); isWeakSet();
Value Check hasValue(); isDefined(); isEmpty(); isNotTruthy(); isNullOrUndefined(); isStrictNullOrUndefined(); isStrictUndefined(); isTruthy(); isUndefined();
Value getValueByKey(); setValueByKey(); getValueByIter(); setValueByIter(); encodeAsJson(); encodeAsHtml(); asString(); getIntValue(); normalizeJsName();
   
Array arrAppend(); arrContains(); arrEvery(); arrFilter(); arrFind(); arrFindIndex(); arrFindLast(); arrFindLastIndex(); arrForEach(); arrFrom(); arrIncludes(); arrIndexOf(); arrLastIndexOf(); arrMap(); arrReduce(); arrSlice(); arrSome(); getLength(); isArray();
polyIsArray(); polyArrIncludes(); polyArrFind(); polyArrFindIndex(); polyArrFindLastIndex(); polyArrFindLast(); polyArrFindLastIndex(); polyArrFrom();
ArrayLike arrContains(); arrEvery(); arrFilter(); arrFind(); arrFindIndex(); arrFindLast(); arrFindLastIndex(); arrForEach(); arrFrom(); arrIncludes(); arrIndexOf(); arrLastIndexOf(); arrMap(); arrReduce(); arrSlice(); arrSome(); getLength(); objEntries(); objValues();
DOM isElement(); isElementLike();
Enum createEnum(); createEnumKeyMap(); createEnumValueMap(); createSimpleMap(); createTypeMap();
Error createCustomError(); isError(); throwError(); throwRangeError(); throwTypeError(); throwUnsupported();
Function fnApply(); fnBind(); fnCall(); createFnDeferredProxy(); createProxyFuncs(); readArgs();
Idle getCancelIdleCallback(); getIdleCallback(); hasIdleCallback(); setDefaultIdleTimeout(); setDefaultMaxExecutionTime();
Iterator createArrayIterator(); createIterator(); createIterable(); createRangeIterator(); iterForOf(); isIterable(); isIterator(); makeIterable(); arrAppend(); arrFrom();
Number getIntValue(); isInteger(); isFiniteNumber(); isNumber();
Math mathAbs(); mathAcos(); mathAsin(); mathAtan(); mathAtan2(); mathCeil(); mathCos(); mathExp(); mathFloor(); mathLog(); mathMax(); mathMin(); mathPow(); mathRandom(); mathRound(); mathSin(); mathSqrt(); mathTan(); mathToInt(); mathTrunc();
Object deepExtend(); isObject(); objAssign(); objCopyProps(); objCreate(); objDeepCopy(); objDeepFreeze(); objDefine(); objDefineAccessors(); objDefineGet(); objDefineProp(); objDefineProps(); objDefineProperties(); objEntries(); objExtend(); objForEachKey(); objFreeze(); objFromEntries(); objGetOwnPropertyDescriptor(); objGetOwnPropertyDescriptors(); objGetOwnPropertyNames(); objGetOwnPropertySymbols(); objHasOwn(); objHasOwnProperty(); objIs(); objIsExtensible(); objIsFrozen(); objIsSealed(); objKeys(); objPreventExtensions(); objPropertyIsEnumerable(); objSeal(); objGetPrototypeOf(); objSetPrototypeOf(); objToString(); objValues();
polyObjEntries(); polyObjIs(); polyObjKeys();
String asString(); getLength(); isString(); strEndsWith(); strIndexOf(); strIsNullOrEmpty(); strIsNullOrWhiteSpace(); strLastIndexOf(); strLeft(); strPadEnd(); strPadStart(); strRepeat(); strRight(); strSlice(); strSplit(); strStartsWith(); strSubstr(); strSubstring(); strSymSplit(); strTrim(); strTrimEnd(); strTrimLeft(); strTrimRight(); strTrimStart(); strLetterCase(); strCamelCase(); strKebabCase(); strSnakeCase(); strUpper(); strLower(); strContains(); strIncludes();
polyStrSubstr(); polyStrTrim(); polyStrTrimEnd(); polyStrTrimStart(); polyStrIncludes();
Symbol WellKnownSymbols (const enum);
getKnownSymbol(); getSymbol(); hasSymbol(); isSymbol(); newSymbol(); symbolFor(); symbolKeyFor();
polyGetKnownSymbol(); polyNewSymbol(); polySymbolFor(); polySymbolKeyFor();

Polyfills are used to automatically backfill runtimes that do not support Symbol, not all of the Symbol functionality is provided.
Timer createTimeout(); createTimeoutWith(); elapsedTime(); perfNow(); setGlobalTimeoutOverrides(); setTimeoutOverrides(); utcNow(); scheduleIdleCallback(); scheduleInterval(); scheduleTimeout(); scheduleTimeoutWith(); hasIdleCallback();
For runtimes that don't support requestIdleCallback normal setTimeout() is used with the values from setDefaultIdleTimeout() and setDefaultMaxExecutionTime();
polyUtcNow();
Conversion encodeAsJson(); encodeAsHtml(); asString(); getIntValue(); normalizeJsName(); strLetterCase(); strCamelCase(); strKebabCase(); strSnakeCase(); strUpper(); strLower();
Cache createCachedValue(); createDeferredCachedValue(); getDeferred(); getWritableDeferred();
Lazy getLazy(); getWritableLazy(); lazySafeGetInst(); safeGetLazy(); safeGetLazy(); setBypassLazyCache();
Safe safe(); safeGetLazy(); safeGet(); safeGetDeferred(); safeGetWritableDeferred(); lazySafeGetInst(); safeGetWritableLazy();
Diagnostic dumpObj();
RegEx createFilenameRegex(); createWildcardRegex(); makeGlobRegex();

Unless otherwise stated in the functions documentation polyfills are used to automatically backfill unsupported functions in older ES5 runtimes

Why Use ts-utils?

1. Better Minification

Using ts-utils helper functions can significantly reduce your bundle size compared to standard JavaScript methods:

// Standard JavaScript - Can't be minified effectively
function stdCode(obj) {
  if (Array.isArray(obj)) {
    for (let i = 0; i < obj.length; i++) {
      if (Object.prototype.hasOwnProperty.call(obj, i)) {
        // Do something
      }
    }
  }
}

// Using ts-utils - Allows better minification
import { isArray, arrForEach, objHasOwnProperty } from "@nevware21/ts-utils";

function optimizedCode(obj) {
  if (isArray(obj)) {
    arrForEach(obj, (value, idx) => {
      if (objHasOwnProperty(obj, idx)) {
        // Do something
      }
    });
  }
}

When minified, the ts-utils version is significantly smaller as function names can be reduced to single characters.

2. Cross-Environment Compatibility

Write code once that works across all environments without worrying about platform-specific APIs:

import { getGlobal, isNode, isWebWorker } from "@nevware21/ts-utils";

// Safely access the global object in any environment
const globalObj = getGlobal();

// Environment detection
if (isNode()) {
  // Node.js specific code
} else if (isWebWorker()) {
  // Web Worker specific code
} else {
  // Browser specific code
}

3. Type Safety

Robust type checking utilities to make your code more reliable:

import { 
  isString, isNumber, isObject, isArray, 
  isNullOrUndefined, isPromise 
} from "@nevware21/ts-utils";

function processValue(value: any) {
  if (isString(value)) {
    return value.toUpperCase();
  } else if (isNumber(value)) {
    return value * 2;
  } else if (isArray(value)) {
    return value.length;
  } else if (isPromise(value)) {
    return value.then(result => result);
  } else if (isNullOrUndefined(value)) {
    return "No value provided";
  }
  
  return "Unknown type";
}

4. Modern ECMAScript Features

Support for newer ECMAScript features with backward compatibility:

import {
  arrFindLast, arrFindLastIndex, // ES2023
  objGetOwnPropertyDescriptors, // ES2017
  strPadStart, strPadEnd, // ES2017
  isBigInt, // ES2020
  isWeakMap, isWeakSet // ES2015+
} from "@nevware21/ts-utils";

// Using ES2023 array methods with backward compatibility
const numbers = [5, 12, 8, 130, 44];
const lastBigNumber = arrFindLast(numbers, num => num > 10); // 44
const lastBigNumberIndex = arrFindLastIndex(numbers, num => num > 10); // 4

// Safe property descriptor access (ES2017)
const descriptors = objGetOwnPropertyDescriptors(myObject);

// String padding (ES2017)
const paddedString = strPadStart("123", 5, "0"); // "00123"
const paddedEnd = strPadEnd("hello", 10, "."); // "hello....."

// Safe type checks for modern types
if (isBigInt(someValue)) {
  // Handle BigInt (ES2020) safely
}

Test Environments

This library is thoroughly tested in:

  • Node.js (16, 18, 20, 22)
  • Modern browsers (via Chromium headless)
  • Web Workers (via Chromium headless)

All polyfill functions are tested against native implementations to ensure full compatibility.

Module Support

The library supports multiple module formats to accommodate different project setups:

  • ES Modules (ESM)
  • CommonJS (CJS)
  • Universal Module Definition (UMD)

Language Support

ES5 Compatibility

This library maintains ES5 compatibility for all v0.x and v1.x releases, ensuring support for any runtime that supports ES5 or higher.

Internal polyfills are used to backfill ES5 functionality which is not provided by older runtimes / browsers.

Future ECMAScript Support

Starting with v2.x, the library plans to update its baseline to target newer ECMAScript versions, reducing the need for polyfills as browser and runtime support evolves.

Browser Support

Chrome Firefox Edge Opera Safari IE
Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔ 9+ ✔

Internet Explorer support will be dropped in v2.x

Polyfills

All of the included polyfills are tested against the current native implementation running in node, browser and worker environments to ensure that they conform to the current specification, these polyfills are only internally used for ES5 compatibility and when running in an environment (mostly IE) that does not support the required function.

Some additional polyfills are provided for simple backward compatibility to enable the utility functions in older environments, however, you don't have to use or include these provided polyfils. If you need to use them you will need to import the pre-packaged "polyfill" bundle (bundle/ts-polyfills-utils.min.js) directly by hosting it on your own CDN or all of the non-internal polyfill implementations are exported so you could implement your own version of the polyfill initializer or more simply provide your own alternatives.

Notes:

  • While some polyfills are provided to "somewhat" support older environments this library does not intend to become a fully fledged polyfill library. And the polyfills provided (or contributed) are just the minimum set that have been required over time. And should be less necessary are time moves forward.
  • Several functions use the Object.defineProperty and therefore support is limited to runtimes or good polyfills that can correctly implement this functionality. (eg. createIterator; createIterable)

TypeScript Support

Built with TypeScript v5.2.2, with minimal requirements of TypeScript v2.8+ for the type definitions.

Size Analysis and Bundle Optimization

Bundle Size Impact

The ts-utils library is designed with size optimization as a primary goal. Each function is independently importable and has been optimized for tree-shaking in modern bundlers like Webpack and Rollup. This allows you to include only what you need in your final bundle.

Here's a comparison of bundle sizes when using ts-utils versus standard JavaScript approaches:

Scenario Standard JS With ts-utils Size Reduction
Basic type checking ~1.2KB ~0.3KB ~75%
Array operations ~0.9KB ~0.4KB ~55%
String utilities ~1.5KB ~0.6KB ~60%
Object helpers ~2.1KB ~0.8KB ~62%

For detailed byte-level measurements and concrete size optimization strategies, check out our Bundle Size Optimization Guide.

Note: Actual size savings depend on your specific usage patterns, minification settings, and bundler configuration.

When to Use ts-utils for Repeated Functions

You should consider using ts-utils helper functions when:

  1. Your code uses the same operations repeatedly: If you're frequently checking types, manipulating arrays/objects, or working with strings, using ts-utils can reduce repetition and improve minification.

  2. Bundle size is a concern: For applications where download size matters (e.g., mobile web apps, SPAs), ts-utils can significantly reduce your bundle size through better minification.

  3. Cross-environment compatibility is needed: When your code needs to run across Node.js, browsers, and web workers without environment-specific code paths.

  4. You want better tree-shaking: The library is designed to allow bundlers to eliminate unused code effectively.

  5. Consistent API access is important: ts-utils provides a unified API for accessing functionality that might be implemented differently across environments.

For example, instead of repeating this pattern across your codebase:

// Before: Multiple instances of this pattern across your code
if (typeof value === 'object' && value !== null && Array.isArray(value)) {
  for (let i = 0; i < value.length; i++) {
    if (Object.prototype.hasOwnProperty.call(value, i)) {
      // Do something with value[i]
    }
  }
}

Use ts-utils to make it more concise and minification-friendly:

// After: More concise, better minification
import { isArray, arrForEach, objHasOwnProperty } from "@nevware21/ts-utils";

if (isArray(value)) {
  arrForEach(value, (item, idx) => {
    if (objHasOwnProperty(value, idx)) {
      // Do something with item
    }
  });
}

For more information on performance and minification benefits, see our Usage Guide.

For detailed documentation on all available utilities, refer to the main documentation site.

License

MIT

About

Comprehensive TypeScript/JavaScript utility library with cross-environment support (Node.js, browser, web worker) providing helper functions, polyfills (ES5-ES2023), type checking utilities, and optimized implementations for better minification and code readability.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •