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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@fennecstudio/utils

v1.9.7

Published

A TypeScript utility library with common helper functions.

Readme

@fennecstudio/utils

A TypeScript utility library with common helper functions.

Installation

npm install @fennecstudio/utils

Usage

import { formatDate, isEmail, chunk } from '@fennecstudio/utils';

API Reference

Table of Contents


utils

addDate | areIds | arraysContainSameValues | atob | base64Decode | base64Encode | basename | btoa | byId | camelCase | camelCaseKeys | capitalize | caseInsensitiveCompare | caseInsensitiveIncludes | chunk | clean | cleanObject | clone | concat | contains | createGatewayEvent | createGroups | createSnsEvent | deduplicate | difference | ensureArray | every | extension | findBy | findById | formatCurrency | formatDate | formatPercentage | formatPrice | generateCode | generateId | generateKey | generateUuid | getCreditCardType | getCurrencySymbol | groupBy | hasAny | hasLength | hasMany | hasNone | hasOne | id | ids | ignoreCase | includes | intersect | isArray | isBoolean | isBuffer | isDate | isEmail | isEmptyObject | isEqual | isError | isExpired | isId | isInTime | isJson | isNullOrUndefined | isNumber | isObject | isOlderThan | isString | joinWithAnd | key | keyify | maxValue | merge | minValue | now | omit | orderNumber | parseEmail | parseErrorMessage | parseFileType | parseFullName | parseGatewayMessage | parseJSON | parseSnsMessage | past | pick | pickWithout | plural | pretty | push | random | randomInRange | remove | removeEmptyObjects | removeEmptyProperties | round | some | sortBy | split | splitEmails | splitFullName | stringify | test | titleCase | toBoolean | toHash | toPrice | toSnakeCase | unique | wait | without

addDate

addDate(date: any, time: any): void

Adds time intervals to a date

Parameters:

  • date any - - The date to add time to (string or Date object)
  • time any - - Object containing time intervals to add (seconds, minutes, hours, days)

Returns: - The new date with added time

Example:

// Add 2 hours to current date
addDate(new Date(), { hours: 2 })

// Add multiple intervals
addDate('2024-01-01', { days: 5, hours: 3, minutes: 30 })

// Add from ISO string
addDate('2024-01-01T12:00:00Z', { seconds: 45 })

areIds

areIds(ids: string[]): void

Checks if all strings in the array are valid IDs (32 characters long)

Parameters:

  • ids any - - Array of strings to validate

Returns: - True if all strings are valid IDs, false otherwise

Example:

areIds(['a'.repeat(32), 'b'.repeat(32)]) // returns true
areIds(['short', 'ids']) // returns false
areIds(['a'.repeat(32), 'invalid']) // returns false

arraysContainSameValues

arraysContainSameValues(arr1?: any[], arr2?: any[]): boolean

Checks if two arrays contain the same values regardless of order

Parameters:

  • arr1 any - - First array to compare
  • arr2 any - - Second array to compare

Returns: - True if arrays contain the same values, false otherwise

Example:

arraysContainSameValues([1, 2, 3], [3, 2, 1]) // returns true
arraysContainSameValues([1, 2], [1, 2, 3]) // returns false
arraysContainSameValues([], []) // returns true
arraysContainSameValues(undefined, undefined) // returns true

Remarks: This function performs a shallow comparison using strict equality (===). For deep object comparison, use with primitive values or references.

atob

atob(data: any, encoding?: BufferEncoding): void

Decodes a base64 encoded string

Parameters:

  • data any - - The base64 encoded data to decode
  • encoding any - - The character encoding to use

Returns: - The decoded string, or empty string if decoding fails

Example:

atob('SGVsbG8gV29ybGQ=') // returns 'Hello World'
atob('SGVsbG8=', 'utf-8') // returns 'Hello'

Remarks: This function is for Node.js environments only. Returns empty string in browser environments.

base64Decode

base64Decode(base64Str: any): void

Decodes a base64 string back to its original value

Parameters:

  • base64Str any - - The base64 encoded string to decode

Returns: - The decoded value (string or parsed object), or empty string if decoding fails

Example:

base64Decode('aGVsbG8=') // returns 'hello'
base64Decode('eyJmb28iOiJiYXIifQ==') // returns { foo: 'bar' }

base64Encode

base64Encode(input: string | object): void

Encodes a string or object to base64 format

Parameters:

  • input any - - The string or object to encode

Returns: - Base64 encoded string, or empty string if encoding fails

Example:

base64Encode('hello') // returns 'aGVsbG8='
base64Encode({ foo: 'bar' }) // returns 'eyJmb28iOiJiYXIifQ=='

basename

basename(uri: string): void

Extracts the filename without extension from a file path

Parameters:

  • uri any - - The file path or URI

Returns: - The filename without extension, or undefined if no filename found

Example:

basename('/path/to/file.txt') // returns 'file'
basename('C:\\Users\\file.doc') // returns 'file'
basename('document.pdf') // returns 'document'
basename('/path/to/folder/') // returns undefined

Remarks: Handles both forward slashes (/) and backslashes () as path separators.

btoa

btoa(data: any): void

Encodes data to base64

Parameters:

  • data any - - The data to encode

Returns: - The base64 encoded string, or empty string if encoding fails

Example:

btoa('Hello World') // returns 'SGVsbG8gV29ybGQ='
btoa('test') // returns 'dGVzdA=='

Remarks: This function is for Node.js environments only. Returns empty string in browser environments.

byId

Deprecated: Use findById() instead for better naming clarity

byId(items: any[], id: string): void

Finds an item by its id property

Parameters:

  • items any - - A collection of objects
  • id any - - The unique identifier on which to match against the 'id' field

Returns: - The first item with matching id, or undefined

Example:

const items = [{ id: '1', name: 'Alice' }, { id: '2', name: 'Bob' }]
byId(items, '2') // returns { id: '2', name: 'Bob' }

camelCase

camelCase(str: string): string

Converts a string to camelCase format

Parameters:

  • str any - - The string to convert to camelCase

Returns: - The string in camelCase format

Example:

camelCase('hello world') // returns 'helloWorld'
camelCase('foo-bar-baz') // returns 'fooBarBaz'
camelCase('user_name') // returns 'userName'
camelCase('PascalCase') // returns 'pascalCase'

Remarks: Removes all non-alphanumeric characters and capitalizes the first letter after each one. Ensures the first character is lowercase.

camelCaseKeys

camelCaseKeys(obj: any): any

Recursively converts object keys from snake_case to camelCase

Parameters:

  • obj any - - The object to convert

Returns: - Object with camelCase keys

Example:

camelCaseKeys({ first_name: 'John', last_name: 'Doe' })
// returns { firstName: 'John', lastName: 'Doe' }

camelCaseKeys({ user_info: { user_name: 'john' } })
// returns { userInfo: { userName: 'john' } }

camelCaseKeys([{ user_id: 1 }, { user_id: 2 }])
// returns [{ userId: 1 }, { userId: 2 }]

Remarks: - Handles nested objects and arrays recursively

  • Preserves Date objects without conversion
  • Non-object values are returned as-is

capitalize

capitalize(str: string): void

Capitalizes the first letter of a string

Parameters:

  • str any - - The string to capitalize

Returns: - The string with the first letter capitalized

Example:

capitalize('hello') // returns 'Hello'
capitalize('world') // returns 'World'
capitalize('123abc') // returns '123abc'

caseInsensitiveCompare

caseInsensitiveCompare(str1: string, str2: string): boolean

Compares two strings case-insensitively

Parameters:

  • str1 any - - First string to compare
  • str2 any - - Second string to compare

Returns: - True if strings are equal ignoring case, false otherwise

Example:

caseInsensitiveCompare('Hello', 'hello') // returns true
caseInsensitiveCompare('ABC', 'abc') // returns true
caseInsensitiveCompare('foo', 'bar') // returns false

caseInsensitiveIncludes

caseInsensitiveIncludes(str: string, arr?: string[]): boolean

Checks if an array contains a string (case-insensitive)

Parameters:

  • str any - - The string to search for
  • arr any - - The array to search in

Returns: - True if the string is found in the array (case-insensitive), false otherwise

Example:

caseInsensitiveIncludes('HELLO', ['hello', 'world']) // returns true
caseInsensitiveIncludes('foo', ['bar', 'baz']) // returns false
caseInsensitiveIncludes('Test', ['test', 'TEST', 'TeSt']) // returns true

chunk

chunk(array: T[] | null | undefined, size?: number): T[][]

Creates an array of elements split into groups the length of size If collection can't be split evenly, the final chunk will be the remaining elements

Parameters:

  • array any - - The array to process
  • size any - - The length of each chunk

Returns: - Returns the new array containing chunks

Example:

chunk([1, 2, 3, 4, 5], 2) // returns [[1, 2], [3, 4], [5]]
chunk(['a', 'b', 'c', 'd'], 3) // returns [['a', 'b', 'c'], ['d']]
chunk([1, 2, 3, 4, 5, 6]) // returns [[1, 2, ..., 100]] (default size 100)
chunk([], 5) // returns []

Remarks: - Returns empty array if input array is null, undefined, or empty

  • Returns empty array if size is less than 1
  • Last chunk may contain fewer elements if array length is not evenly divisible

clean

clean(val: any): void

Cleans a string by escaping quotes and replacing angle brackets

Parameters:

  • val any - - The value to clean

Returns: - The cleaned string

Example:

clean('Hello "World"') // returns 'Hello \\"World\\"'
clean('<script>alert()</script>') // returns '[script]alert()[/script]'
clean('test < 5 && test > 0') // returns 'test [ 5 && test ] 0'

Remarks: - Escapes double quotes with backslash

  • Replaces < with [
  • Replaces > with ]
  • Returns unchanged if value is not a string

cleanObject

cleanObject(obj: Record<string, any>): Record<string, any>

Recursively removes null, undefined, and empty string values from an object

Parameters:

  • obj any - - The object to clean

Returns: - The cleaned object

Example:

cleanObject({ name: 'John', age: null, city: '' })
// returns { name: 'John' }

cleanObject({ user: { name: 'John', email: null }, items: ['a', '', 'b'] })
// returns { user: { name: 'John' }, items: ['a', 'b'] }

cleanObject({ empty: {}, data: { value: null } })
// returns {}

Remarks: - Modifies the object in place

  • Recursively processes nested objects and arrays
  • Removes empty arrays and objects after cleaning
  • Non-object values are returned unchanged

clone

clone(value: any): void

Creates a shallow copy of a value

Parameters:

  • value any - - The value to clone

Returns: - A shallow copy of the value

Example:

clone({ a: 1, b: 2 }) // returns { a: 1, b: 2 }
clone([1, 2, 3]) // returns [1, 2, 3]
clone('string') // returns 'string'
clone(42) // returns 42

Remarks: Only performs shallow cloning - nested objects/arrays still reference the same values. For deep cloning, use a dedicated deep clone utility.

concat

concat(a?: any[], b?: any[], c?: any[], d?: any[], e?: any[], f?: any[], g?: any[], h?: any[], i?: any[]): void

Concatenates multiple arrays into a single array

Parameters:

  • a any - - First array
  • b any - - Second array
  • c any - - Third array
  • d any - - Fourth array
  • e any - - Fifth array
  • f any - - Sixth array
  • g any - - Seventh array
  • h any - - Eighth array
  • i any - - Ninth array

Returns: - A new array containing all elements from the input arrays

contains

contains(array: any[], x: any): void

Checks if an array contains a specific value

Parameters:

  • array any - - The array to search
  • x any - - The value to search for

Returns: - True if the value is found, false otherwise

createGatewayEvent

createGatewayEvent(body?: any, params?: any): void

Creates a json object in the format used by AWS Gateway events Used primarily for testing

Parameters:

  • body any -
  • params any -

createGroups

Deprecated: Use chunk() instead Creates an array of arrays, each containing a subset of the original array This is useful for breaking up large arrays into smaller chunks

createGroups(arr: any[], groupSize?: any): void

Parameters:

  • arr any -
  • groupSize any -

createSnsEvent

createSnsEvent(message: any): void

Creates a mock SNS event object for testing

Parameters:

  • message any - - The message to include in the SNS event

Returns: - A mock SNS event object

deduplicate

deduplicate(array: any[]): void

Removes duplicate values from the given array

Parameters:

  • array any - - The array to deduplicate

Returns: - A new array with unique values, excluding falsy values

Example:

deduplicate([1, 2, 2, 3, 3, 3]) // returns [1, 2, 3]
deduplicate(['a', 'b', 'a', 'c']) // returns ['a', 'b', 'c']
deduplicate([1, null, 2, undefined, 3]) // returns [1, 2, 3]
deduplicate([true, false, true]) // returns [true]

Remarks: - Uses Set for deduplication

  • Filters out falsy values (null, undefined, false, 0, '', NaN)
  • Maintains insertion order

difference

difference(array1: any[], array2: any[]): any[]

Returns the difference between two arrays

Parameters:

  • array1 any - - The array to compare from
  • array2 any - - The array to compare against

Returns: - An array of items that are in array1 but not in array2

Example:

difference([1, 2, 3, 4], [2, 4]) // returns [1, 3]
difference(['a', 'b', 'c'], ['b']) // returns ['a', 'c']
difference([1, 2], [3, 4]) // returns [1, 2]

Remarks: Uses Set for efficient lookup. Only performs shallow comparison.

ensureArray

ensureArray(array: any | any[]): any[]

Ensures that the given value is an array

Parameters:

  • array any - - The value to ensure is an array

Returns: - An array containing the value; returns empty array for null/undefined

Example:

ensureArray(5) // returns [5]
ensureArray([1, 2, 3]) // returns [1, 2, 3]
ensureArray('hello') // returns ['hello']
ensureArray(null) // returns []
ensureArray(undefined) // returns []

Remarks: - Returns empty array for null or undefined

  • Wraps non-array values in an array
  • Returns arrays unchanged

every

every(items: any[], predicate: any): void

Tests whether all elements in the array pass the test implemented by the provided function

Parameters:

  • items any - - The array to test
  • predicate any - - The function to test each element

Returns: - True if all elements pass the test, false otherwise

extension

extension(filename: string): void

Parses the file extension from the given filename, including the '.'

Parameters:

  • filename any -

Returns: - The file extension of the given filename

findBy

findBy(items: any[], prop: string, value: any): void

Finds the first item in a collection of objects that matches the given id

Parameters:

  • items any - - A collection of objects
  • prop any - = The name of the property to match
  • value any - - The value on which to match against the provided property name

Returns: - The first item in the collection that matches the given id

findById

findById(items: any[], id: string | number): void

Finds the first item in a collection of objects that matches the given id

Parameters:

  • items any - - A collection of objects
  • id any - - The unique identifier on which to match against the 'id' property

Returns: - The first item in the collection that matches the given id

formatCurrency

formatCurrency(amount: number, locale?: string, currency?: string): void

Formats a number as a currency string using the Intl.NumberFormat API

Parameters:

  • amount any - - The number to format as float
  • locale any - - The locale to use for formatting (default: 'en-US')
  • currency any - - The currency code to use (default: 'USD')

Returns: - A formatted currency string in the specified locale and currency

Example:

formatCurrency(1234.56) // returns "$1,234.56"
formatCurrency(1234.56, 'de-DE', 'EUR') // returns "1.234,56 €"

formatDate

formatDate(input: any, formatTemplate?: string): string

Formats a date using the Intl.DateTimeFormat API

Parameters:

  • input any - - The date to format
  • formatTemplate any - - The format template to use (default: 'MM/dd/yyyy')
  • 'timestamp': formats as 'MM/dd/yyyy h:mm a z'
  • 'relative': formats as relative time with suffix (e.g., '2 days ago')
  • 'short': formats as 'MM/dd/yyyy'
  • 'friendly': formats as 'MMM do yyyy'

Returns: - A formatted date string

Example:

formatDate(new Date()) // returns "MM/dd/yyyy"
formatDate(new Date(), 'MM/dd/yyyy') // returns "MM/dd/yyyy"
formatDate(new Date(), 'MM/dd/yyyy h:mm a z') // returns "MM/dd/yyyy 12:00 AM UTC"
formatDate(new Date(), 'timestamp') // returns "MM/dd/yyyy 12:00 AM UTC"
formatDate(new Date(), 'relative') // returns "less than a minute ago"
formatDate(new Date(), 'short') // returns "MM/dd/yyyy"
formatDate(new Date(), 'friendly') // returns "Jan 1st 2023"

formatPercentage

formatPercentage(num: number, precision?: number): string

formatPrice

formatPrice(num: number, precision?: number): void

Formats a number as a price string

Parameters:

  • num any - - The number to format as float
  • precision any - - The number of decimal places to include (default: 0)

Returns: - A formatted price string in the specified locale and currency

Example:

formatPrice(1234.56) // returns "$1,234.56"
formatPrice(1234.56, 2) // returns "$1,234.56"
formatPrice(1234.56, 0) // returns "$1,234"

generateCode

generateCode(numDigits?: number): string

Generates a random numeric code with the specified number of digits

Parameters:

  • numDigits any - - The number of digits in the code (default: 6)

Returns: - A random numeric code as a string

generateId

generateId(iterations?: any): void

Generates a unique ID by concatenating UUIDs

Parameters:

  • iterations any - - The number of UUIDs to concatenate (default: 1)

Returns: - A unique ID string

generateKey

generateKey(length?: any): void

Generates a random alphanumeric key

Parameters:

  • length any - - The length of the key (default: 5)

Returns: - A random alphanumeric string

generateUuid

generateUuid(separator?: any): string

Generates a RFC 4122 compliant UUID v4

Parameters:

  • separator any - - The separator to use between UUID segments

Returns: - A UUID string

Example:

generateUuid() // returns '550e8400e29b41d4a716446655440000'
generateUuid('-') // returns '550e8400-e29b-41d4-a716-446655440000'
generateUuid('_') // returns '550e8400_e29b_41d4_a716_446655440000'

Remarks: - Generates cryptographically strong random values

  • Compliant with RFC 4122 UUID v4 specification
  • Default format: 32 characters without dashes
  • With separator '-': 8-4-4-4-12 format

getCreditCardType

getCreditCardType(cardNumber?: string): void

Determines the credit card type based on the card number

Parameters:

  • cardNumber any - - The credit card number to analyze

Returns: - The card type (VISA, MASTERCARD, AMEX, DISCOVER, JCB, DINERSCLUB) or undefined

getCurrencySymbol

getCurrencySymbol(currencyCode: string): void

Gets the currency symbol for a given currency code

Parameters:

  • currencyCode any - - The ISO currency code (e.g., 'USD', 'EUR')

Returns: - The currency symbol or '$' as fallback

groupBy

groupBy(collection: any[], property?: string): void

Groups an array of objects by a specified property

Parameters:

  • collection any - - The array of objects to group
  • property any - - The property name to group by

Returns: - An object with grouped items, keyed by the property value

Example:

const users = [
  { id: 1, role: 'admin' },
  { id: 2, role: 'user' },
  { id: 3, role: 'admin' }
]
groupBy(users, 'role')
// returns { admin: [{id: 1, role: 'admin'}, {id: 3, role: 'admin'}], user: [{id: 2, role: 'user'}] }

const items = [{ category: 'A', value: 1 }, { category: 'B', value: 2 }, { category: 'A', value: 3 }]
groupBy(items, 'category')
// returns { A: [{ category: 'A', value: 1 }, { category: 'A', value: 3 }], B: [{ category: 'B', value: 2 }] }

hasAny

hasAny(items?: any[]): void

Checks if an array has any elements

Parameters:

  • items any - - The array to check

Returns: - True if the array has elements, false otherwise

hasLength

hasLength(items?: any[], min?: number): boolean

Checks if an array has a minimum number of elements

Parameters:

  • items any - - The array to check
  • min any - - The minimum number of elements (default: 1)

Returns: - True if the array has at least the minimum number of elements

hasMany

hasMany(items: any[]): void

Checks if an array has more than one element

Parameters:

  • items any - - The array to check

Returns: - True if the array has 2 or more elements

hasNone

hasNone(items?: any[]): void

Checks if an array has no elements

Parameters:

  • items any - - The array to check

Returns: - True if the array is empty or null/undefined

hasOne

hasOne(items?: any[]): void

Checks if an array has exactly one element

Parameters:

  • items any - - The array to check

Returns: - True if the array has exactly one element

id

id(): void

Generates a unique ID using UUID v4

Returns: - A UUID string

ids

ids(items?: any[]): void

Extracts and deduplicates IDs from an array of objects

Parameters:

  • items any - - Array of objects with id properties

Returns: - Array of unique IDs

ignoreCase

ignoreCase(value: string): void

Creates a case-insensitive regular expression for exact matching

Parameters:

  • value any - - The string to create a regex for

Returns: - A case-insensitive RegExp object

includes

includes(items?: any[], value: any): void

Checks if an array includes a specific value

Parameters:

  • items any - - The array to search
  • value any - - The value to search for

Returns: - True if the value is found, false otherwise

intersect

intersect(arr1: any, arr2: any): void

Returns the intersection of two arrays

Parameters:

  • arr1 any -
  • arr2 any -

isArray

isArray(value: any): void

Checks if a value is an array

Parameters:

  • value any - - The value to check

Returns: - True if the value is an array

isBoolean

isBoolean(value: string): void

Checks if a string represents a boolean value

Parameters:

  • value any - - The string to check

Returns: - True if the string is 'true' or 'false' (case-insensitive)

isBuffer

isBuffer(value: any): void

Checks if a value is a Buffer

Parameters:

  • value any - - The value to check

Returns: - True if the value is a Buffer

isDate

isDate(input: any): boolean

Checks if a value is a valid date or date string

Parameters:

  • input any - - The value to check

Returns: - True if the value is a valid date

isEmail

isEmail(email: string): void

Checks if a string is a valid email address

Parameters:

  • email any - - The string to check

Returns: - True if the string is a valid email format

isEmptyObject

isEmptyObject(obj?: any): void

Checks if an object is empty (has no own properties)

Parameters:

  • obj any - - The object to check

Returns: - True if the object is empty or falsy

isEqual

isEqual(value: any, other: any): boolean

Performs a deep comparison between two values to determine if they are equivalent.

Note: This method supports comparing arrays, array buffers, booleans, date objects, error objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays. Object objects are compared by their own, not inherited, enumerable properties. Functions and DOM nodes are not supported.

Parameters:

  • value any - - The value to compare
  • other any - - The other value to compare

Returns: - True if the values are equivalent, false otherwise

Example:

var object = { 'user': 'fred' };
var other = { 'user': 'fred' };

isEqual(object, other);
// => true

object === other;
// => false

isError

isError(value: any): void

Checks if a value is an Error object

Parameters:

  • value any - - The value to check

Returns: - True if the value is an Error instance

isExpired

isExpired(expiresOn: string | Date, ttl?: any): void

Checks if a date has expired (is in the past)

Parameters:

  • expiresOn any - - The expiration date
  • ttl any - - Optional time-to-live to add to the expiration date

Returns: - True if the date has expired

isId

isId(id?: string): boolean

Checks if a string is a valid ID (32 characters long)

Parameters:

  • id any - - The string to check

Returns: - True if the string is a valid ID

isInTime

isInTime(date: any, ttl?: any): void

Checks if a date is within a specified time range from now

Parameters:

  • date any - - The date to check
  • ttl any - - Time-to-live object specifying the range

Returns: - True if the date is within the specified time range

isJson

isJson(value: string): void

Checks if a string is valid JSON

Parameters:

  • value any - - The string to check

Returns: - True if the string is valid JSON

isNullOrUndefined

isNullOrUndefined(value: any): void

Checks if a value is null or undefined

Parameters:

  • value any - - The value to check

Returns: - True if the value is null or undefined

isNumber

isNumber(value: any): void

Checks if a value is a valid number

Parameters:

  • value any - - The value to check

Returns: - True if the value is a finite number

isObject

isObject(input: any): boolean

Checks if a value is an object (not array, null, or primitive)

Parameters:

  • input any - - The value to check

Returns: - True if the value is an object

isOlderThan

isOlderThan(date: any, ttl?: any): void

Checks if a date is older than a specified time period or current time

Parameters:

  • date any - - The date to check
  • ttl any - - Optional time period to add to current time for comparison

Returns: - True if the date is older than the comparison time

isString

isString(input: any): boolean

Checks if a value is a string

Parameters:

  • input any - - The value to check

Returns: - True if the value is a string

joinWithAnd

joinWithAnd(array: string[]): void

Joins an array of strings with commas and 'and' for the last item

Parameters:

  • array any -

key

key(length?: any): void

Generates a random alphanumeric key (alias for generateKey)

Parameters:

  • length any - - The length of the key (default: 5)

Returns: - A random alphanumeric string

keyify

keyify(value: string): string

Converts a string to a URL-friendly key format

Parameters:

  • value any - - The string to convert

Returns: - A URL-friendly string with lowercase letters, numbers, and hyphens

maxValue

maxValue(arr: number[]): void

Finds the maximum value in an array of numbers

Parameters:

  • arr any - - Array of numbers

Returns: - The maximum value

merge

merge(list?: any[], updates?: any[], prop?: string): void

Merges updates into a list based on a matching property

Parameters:

  • list any - - The list to update
  • updates any - - Array of updates to apply
  • prop any - - Property name to match on (default: 'id')

Returns: - The updated list

minValue

minValue(arr: number[]): void

Finds the minimum value in an array of numbers

Parameters:

  • arr any - - Array of numbers

Returns: - The minimum value

now

now(): void

Returns the current date and time

Returns: - A new Date object representing the current time

omit

omit(obj: T | null | undefined, keys: string[] | string, additionalKeys?: string[]): Partial<T>

Returns a new object with all keys except the specified keys (opposite of pick)

Parameters:

  • obj any - - The source object
  • keys any - - Array of keys or individual key arguments to omit
  • additionalKeys any - - Additional keys to omit when using string format

Returns: - A new object without the specified keys

Example:

const user = { id: 1, name: 'John', email: '[email protected]', password: 'secret' }

// Array format
omit(user, ['password']) // returns { id: 1, name: 'John', email: '[email protected]' }

// Variadic format
omit(user, 'password', 'email') // returns { id: 1, name: 'John' }

// Null safety
omit(null, ['key']) // returns {}

Remarks: - Supports both array and variadic argument styles

  • Returns empty object if input is null or undefined
  • Keys that don't exist in the source object are ignored

orderNumber

orderNumber(len?: number): void

Generates a random order number using alphanumeric characters

Parameters:

  • len any - - The length of the order number (default: 8)

Returns: - A random order number string

parseEmail

parseEmail(inputString: string): void

Parses an email string that may include a display name

Parameters:

Returns: - Object with address and optional displayName properties

parseErrorMessage

parseErrorMessage(err: any): void

Extracts an error message from various error formats

Parameters:

  • err any - - The error object, string, or data structure

Returns: - The error message string or undefined

parseFileType

parseFileType(filePath: string): string

Tries to determine a files content type by its extension

Parameters:

  • filePath any - - file path or filename

parseFullName

parseFullName(fullName: string): { firstName: string; lastName: string }

Parses a full name into first and last name components

Parameters:

  • fullName any - - The full name string to parse

Returns: - Object with firstName and lastName properties

parseGatewayMessage

parseGatewayMessage(event?: any): void

Parses an AWS API Gateway event into a structured message

Parameters:

  • event any - - The API Gateway event object

Returns: - Object with parsed body, headers, and params

parseJSON

parseJSON(input: any): void

Safely parses JSON, returning the original input if parsing fails

Parameters:

  • input any - - The input to parse as JSON

Returns: - Parsed JSON object or original input if parsing fails

Example:

parseJSON('{"name":"John"}') // returns { name: 'John' }
parseJSON('[1,2,3]') // returns [1, 2, 3]
parseJSON('invalid json') // returns 'invalid json'
parseJSON(null) // returns null
parseJSON({ already: 'parsed' }) // returns { already: 'parsed' }

Remarks: - Returns input unchanged if null, undefined, or not a string

  • Returns input if JSON parsing fails
  • Never throws errors

parseSnsMessage

parseSnsMessage(event?: any): void

Parses an AWS SNS message from an event

Parameters:

  • event any - - The SNS event object

Returns: - The parsed message or empty object if parsing fails

past

past(num: number, name?: any): void

Creates a date in the past by subtracting time from now

Parameters:

  • num any - - Number of time units to subtract
  • name any - - Time unit ('m', 'min', 'mins', 'h', 'hour', 'hours')

Returns: - A Date object in the past

pick

pick(obj: T, keys: string[] | string, additionalKeys?: string[]): Partial<T>

Returns a new object with only the specified keys

Parameters:

  • obj any - - The source object
  • keys any - - Array of keys or individual key arguments to include
  • additionalKeys any - - Additional keys when using string format

Returns: - A new object containing only the specified keys

Example:

const user = { id: 1, name: 'John', email: '[email protected]', age: 30 }

// Array format
pick(user, ['name', 'email']) // returns { name: 'John', email: '[email protected]' }

// Variadic format
pick(user, 'name', 'email') // returns { name: 'John', email: '[email protected]' }

// Non-existent keys are ignored
pick(user, ['name', 'nonexistent']) // returns { name: 'John' }

Remarks: Supports both array and variadic argument styles for specifying keys. Keys that don't exist in the source object are ignored.

pickWithout

pickWithout(obj: T, keys: string[]): Partial<T>

Returns a new object with all keys except the specified keys

Parameters:

  • obj any -
  • keys any -

plural

plural(word?: any, count?: any, suffix?: any): void

Returns the plural form of a word based on count

Parameters:

  • word any - - The word to pluralize
  • count any - - The count to determine if plural is needed
  • suffix any - - The suffix to add for pluralization (default: 's')

Returns: - The word in singular or plural form

pretty

pretty(obj?: any, indent?: any): void

Converts an object to a pretty-printed JSON string

Parameters:

  • obj any - - The object to stringify
  • indent any - - Number of spaces for indentation (default: 4)

Returns: - Pretty-printed JSON string

push

push(array?: any[], insert: any, uniq?: boolean): void

Pushes one or more items to an array with optional uniqueness check

Parameters:

  • array any - - The array to push to
  • insert any - - The item(s) to insert
  • uniq any - - Whether to check for uniqueness (default: true)

Returns: - The modified array

random

random(max?: number): void

Generates a random integer between 0 and max (exclusive)

Parameters:

  • max any - - The maximum value (exclusive, default: 100)

Returns: - A random integer

randomInRange

randomInRange(min: number, max: number): number

Generates a random integer within a specified range (inclusive)

Parameters:

  • min any - - The minimum value (inclusive)
  • max any - - The maximum value (inclusive)

Returns: - A random integer within the range

remove

remove(array?: any[], value: any): void

Removes all instances of a value from an array

Parameters:

  • array any - - The array to filter
  • value any - - The value to remove

Returns: - A new array with the value removed

removeEmptyObjects

removeEmptyObjects(collection?: any): void

Removes empty objects from a collection

Parameters:

  • collection any - - Array of objects to filter

Returns: - Array with empty objects removed

removeEmptyProperties

removeEmptyProperties(obj: any): void

Removes empty properties (null, undefined, empty string) from an object

Parameters:

  • obj any - - The object to clean

Returns: - A new object with empty properties removed

round

round(num: any, i?: any): void

Rounds a number to specified decimal places

Parameters:

  • num any - - The number to round
  • i any - - Number of decimal places (default: 2)

Returns: - The rounded number

some

some(array: any[], predicate: any): void

Tests whether at least one element passes the provided function

Parameters:

  • array any - - The array to test
  • predicate any - - The function to test each element

Returns: - True if at least one element passes the test

sortBy

sortBy(arr: any[], prop: string, desc?: boolean): void

Sorts an array of objects by a specified property

Parameters:

  • arr any - - The array to sort
  • prop any - - The property name to sort by
  • desc any - - Whether to sort in descending order (default: false)

Returns: - The sorted array

split

split(str: string, delimiter?: any): void

Splits a string by delimiter and deduplicates the result

Parameters:

  • str any - - The string to split
  • delimiter any - - The delimiter to split by (default: ',')

Returns: - Array of unique split values or original string if no delimiter found

splitEmails

splitEmails(emailList: string): string[]

Splits a string of emails separated by commas or whitespace

Parameters:

  • emailList any - - String containing multiple email addresses

Returns: - Array of trimmed email addresses

splitFullName

splitFullName(fullName: string): { firstName: string; lastName: string }

Splits a full name into first and last name components

Parameters:

  • fullName any - - The full name string to split

Returns: - Object with firstName and lastName properties

stringify

stringify(data: any): void

Safely converts data to a string representation

Parameters:

  • data any - - The data to stringify

Returns: - String representation of the data

test

test(str: string, re: any, word?: boolean, flags?: string): void

Tests a string against a regular expression

Parameters:

  • str any - - The string to test
  • re any - - The regular expression pattern
  • word any - - Whether to match whole word only (default: false)
  • flags any - - RegExp flags (default: 'i' for case-insensitive)

Returns: - True if the string matches the pattern

titleCase

titleCase(str: string): string

Converts a string to title case

Parameters:

  • str any - - The string to convert

Returns: - The string in title case format

toBoolean

toBoolean(value: any, defaultValue?: any): void

Converts a value to a boolean

Parameters:

  • value any - - The value to convert
  • defaultValue any - - Default value if input is null/undefined (default: false)

Returns: - Boolean representation of the value

toHash

toHash(array: any[], keyProperty?: any, valueProperty?: string): void

Creates a new object from the given collection of objects, using the value of given property as the hash key

Parameters:

  • array any -
  • keyProperty any -
  • valueProperty any -

toPrice

toPrice(price: number | string, def?: number): number

Ensures the proper formatting of a currency value

Parameters:

  • price any -
  • def any - - default value if the price is not a valid number

toSnakeCase

toSnakeCase(obj: any): any

Recursively converts object keys from camelCase to snake_case

Parameters:

  • obj any - - The object to convert

Returns: - Object with snake_case keys

unique

unique(prefix?: any, suffix?: any): void

Creates a unique value based on the current timestamp Used primarily for testing

Parameters:

  • prefix any -
  • suffix any -

wait

wait(ms: number): void

Waits for the specified number of milliseconds

Parameters:

  • ms any - - The number of milliseconds to wait

Returns: - A promise that resolves after the specified time

without

without(array: T[], values?: T[]): T[]

Returns a new array with specified values removed

Parameters:

  • array any - - The source array
  • values any - - Values to exclude from the result

Returns: - A new array without the specified values


functions

delay | interval | retry

delay

delay(fn: Function, time?: number): void

Executes a function after a delay.

Parameters:

  • fn any - - The function to execute
  • time any - - Delay duration in milliseconds (default: random 1-10 seconds)

Returns: - The timeout ID for clearing with clearTimeout

interval

interval(fn: Function, time?: number, immediate?: boolean): void

Executes a function at regular intervals.

Parameters:

  • fn any - - The function to execute
  • time any - - Interval duration in milliseconds (default: 5 minutes)
  • immediate any - - Whether to execute immediately before starting interval (default: true)

Returns: - The interval ID for clearing with clearInterval

retry

retry(fn: Function, retryWait?: number, maxAttempts?: number): void

Retries a function multiple times with a delay between attempts.

Parameters:

  • fn any - - The function to execute
  • retryWait any - - Milliseconds to wait between retries (default: random 4-6 seconds)
  • maxAttempts any - - Maximum number of attempts (default: 3)

Returns: - The result of the function if successful


html

copyToClipboard | params

copyToClipboard

copyToClipboard(text: string): void

Copies text to the clipboard using the Clipboard API.

Parameters:

  • text any - - The text to copy to clipboard

params

params(name: string, url?: string): void

Extracts a query parameter value from a URL.

Parameters:

  • name any - - The name of the query parameter
  • url any - - The URL to parse (default: current window location)

Returns: - The decoded parameter value, or undefined if not found


rateLimiting

formatRateWindow | getCurrentRateWindow | getRateWindow | isCurrentRateWindow

formatRateWindow

formatRateWindow(date: any): void

Formats a date as a rate window string.

Parameters:

  • date any - - The date to format

Returns: - Formatted string (e.g., "Jan, 1st 2:00 pm")

getCurrentRateWindow

getCurrentRateWindow(): void

Gets the current rate window (start of the current hour).

Returns: - Date object representing the start of the current hour

getRateWindow

getRateWindow(date: any): void

Gets the rate window for a given date (start of that hour).

Parameters:

  • date any - - The date to get the rate window for

Returns: - Date object representing the start of that hour

isCurrentRateWindow

isCurrentRateWindow(date: string | Date): void

Checks if a date falls within the current rate window (same hour).

Parameters:

  • date any - - The date to check (string or Date object)

Returns: - True if the date is in the current rate window, false otherwise


milliseconds

$10minutesAgo | $10minutesFromNow | $10secondsAgo | $12hoursAgo | $1dayAgo | $1hourAgo | $1hourFromNow | $1minuteAgo | $1minuteFromNow | $1monthAgo | $1secondAgo | $1secondFromNow | $1weekAgo | $1weekFromNow | $1yearAgo | $24HoursAgo | $2daysAgo | $2daysFromNow | $2hoursAgo | $2minutesAgo | $2monthsAgo | $2secondsAgo | $2weeksAgo | $2weeksFromNow | $30daysAgo | $30minutesAgo | $30secondsAgo | $3daysFromNow | $3hoursAgo | $3minutesAgo | $3monthsAgo | $3monthsFromNow | $3secondsAgo | $45secondsAgo | $4minutesAgo | $4monthsAgo | $4secondsAgo | $5minutesAgo | $5monthsAgo | $5secondsAgo | $6hoursAgo | $6monthsAgo | $6monthsFromNow | $daysFromNow | $lastWeek | $nextMonth | $nextWeek | $nextYear | $today | $tomorrow | $yesterday | last12hours | last24hours | last30minutes

$10minutesAgo

$10minutesAgo(): void

$10minutesFromNow

$10minutesFromNow(): void

$10secondsAgo

$10secondsAgo(): void

$12hoursAgo

$12hoursAgo(): void

$1dayAgo

$1dayAgo(): void

$1hourAgo

$1hourAgo(): void

$1hourFromNow

$1hourFromNow(): void

$1minuteAgo

$1minuteAgo(): void

$1minuteFromNow

$1minuteFromNow(): void

$1monthAgo

$1monthAgo(): void

$1secondAgo

$1secondAgo(): void

$1secondFromNow

$1secondFromNow(): void

$1weekAgo

$1weekAgo(): void

$1weekFromNow

$1weekFromNow(): void

$1yearAgo

$1yearAgo(): void

$24HoursAgo

$24HoursAgo(): void

$2daysAgo

$2daysAgo(): void

$2daysFromNow

$2daysFromNow(): void

$2hoursAgo

$2hoursAgo(): void

$2minutesAgo

$2minutesAgo(): void

$2monthsAgo

$2monthsAgo(): void

$2secondsAgo

$2secondsAgo(): void

$2weeksAgo

$2weeksAgo(): void

$2weeksFromNow

$2weeksFromNow(): void

$30daysAgo

$30daysAgo(): void

$30minutesAgo

$30minutesAgo(): void

$30secondsAgo

$30secondsAgo(): void

$3daysFromNow

$3daysFromNow(): void

$3hoursAgo

$3hoursAgo(): void

$3minutesAgo

$3minutesAgo(): void

$3monthsAgo

$3monthsAgo(): void

$3monthsFromNow

$3monthsFromNow(): void

$3secondsAgo

$3secondsAgo(): void

$45secondsAgo

$45secondsAgo(): void

$4minutesAgo

$4minutesAgo(): void

$4monthsAgo

$4monthsAgo(): void

$4secondsAgo

$4secondsAgo(): void

$5minutesAgo

$5minutesAgo(): void

$5monthsAgo

$5monthsAgo(): void

$5secondsAgo

$5secondsAgo(): void

$6hoursAgo

$6hoursAgo(): void

$6monthsAgo

$6monthsAgo(): void

$6monthsFromNow

$6monthsFromNow(): void

$daysFromNow

$daysFromNow(days: number): void

$lastWeek

$lastWeek(): void

$nextMonth

$nextMonth(): void

$nextWeek

$nextWeek(): void

$nextYear

$nextYear(): void

$today

$today(): void

$tomorrow

$tomorrow(): void

$yesterday

$yesterday(): void

last12hours

last12hours(): void

last24hours

last24hours(): void

last30minutes

last30minutes(): void

day

addToDay | fromDay | getDayOfWeek | getDaysOfWeek | isDayFormat | lastWeek | lastYear | nextDay | nextWeek | today | toDay | tomorrow | yesterday

addToDay

addToDay(yyyymmdd: string, days: number): string

Adds the specified number of days to the given date string.

Parameters:

  • yyyymmdd string - - The date string in YYYY-MM-DD format
  • days number - - Number of days to add (can be negative to subtract)

Returns: string - The resulting date in YYYY-MM-DD format

fromDay

fromDay(day: string, timezone?: string): Date

Converts a date string to a Date object.

  • Without timezone: Creates a Date at noon (12:00:00) in local time for consistent timezone handling
  • With timezone: Creates a Date at midnight (00:00:00) in the specified timezone

Parameters:

  • day any - - Date string in YYYY-MM-DD format
  • timezone any - - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC'). If provided, the date will be created at midnight in the specified timezone, ensuring the day does not shift during conversion.

Returns: - Date object

getDayOfWeek

getDayOfWeek(dateString: string): dayOfWeek

Gets the day of the week for a given date string.

Parameters:

  • dateString string - - The date string to parse

Returns: dayOfWeek - The day of the week as a lowercase string

getDaysOfWeek

getDaysOfWeek(startDay: string, endDay: string): dayOfWeek[]

Gets all unique days of the week that occur within a date range. Returns an array of unique day names (e.g., ['monday', 'tuesday']) for the given date range.

Parameters:

  • startDay string - - Start date in YYYY-MM-DD format
  • endDay string - - End date in YYYY-MM-DD format (inclusive)

Returns: dayOfWeek[] - Array of unique day names as lowercase strings

isDayFormat

isDayFormat(yyyymmdd: string): void

Validates if a string matches the YYYY-MM-DD date format and represents a valid date

Parameters:

  • yyyymmdd any - - The string to validate

Returns: - True if the string matches YYYY-MM-DD format and is a valid date, false otherwise

lastWeek

lastWeek(timezone?: string): string

Returns the date one week ago from today as a string in YYYY-MM-DD format.

Parameters:

  • timezone string - - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')

Returns: string - Date one week ago in YYYY-MM-DD format

lastYear

lastYear(timezone?: string): string

Returns the date one year ago from today as a string in YYYY-MM-DD format.

Parameters:

  • timezone string - - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')

Returns: string - Date one year ago in YYYY-MM-DD format

nextDay

nextDay(yyyymmdd: string): string

Returns the next day for a given date string.

Parameters:

  • yyyymmdd string - - The date string in YYYY-MM-DD format

Returns: string - The next day in YYYY-MM-DD format

nextWeek

nextWeek(timezone?: string): string

Returns the date one week from today as a string in YYYY-MM-DD format.

Parameters:

  • timezone string - - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')

Returns: string - Date one week from today in YYYY-MM-DD format

today

today(timezone?: string): string

Returns today's date as a string in YYYY-MM-DD format.

Parameters:

  • timezone string - - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')

Returns: string - Today's date in YYYY-MM-DD format

toDay

toDay(date?: Date): string

Converts a Date object to a string in YYYY-MM-DD format.

Parameters:

  • date Date - - The date to convert. Defaults to current date if not provided.

Returns: string - The date in YYYY-MM-DD format

tomorrow

tomorrow(timezone?: string): string

Returns tomorrow's date as a string in YYYY-MM-DD format.

Parameters:

  • timezone string - - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')

Returns: string - Tomorrow's date in YYYY-MM-DD format

yesterday

yesterday(timezone?: string): string

Returns yesterday's date as a string in YYYY-MM-DD format.

Parameters:

  • timezone string - - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')

Returns: string - Yesterday's date in YYYY-MM-DD format