A TypeScript utility library with common helper functions.
npm install @fennecstudio/utilsA TypeScript utility library with common helper functions.
``bash`
npm install @fennecstudio/utils
`typescript`
import { formatDate, isEmail, chunk } from '@fennecstudio/utils';
- utils
- functions
- html
- rateLimiting
- milliseconds
- day
---
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
`typescript`
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:
`typescript
// 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 })
`
`typescript`
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:
`typescript`
areIds(['a'.repeat(32), 'b'.repeat(32)]) // returns true
areIds(['short', 'ids']) // returns false
areIds(['a'.repeat(32), 'invalid']) // returns false
`typescript`
arraysContainSameValues(arr1?: any[], arr2?: any[]): boolean
Checks if two arrays contain the same values regardless of order
Parameters:
- arr1 any - - First array to comparearr2
- any - - Second array to compare
Returns: - True if arrays contain the same values, false otherwise
Example:
`typescript`
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.
`typescript`
atob(data: any, encoding?: BufferEncoding): void
Decodes a base64 encoded string
Parameters:
- data any - - The base64 encoded data to decodeencoding
- any - - The character encoding to use
Returns: - The decoded string, or empty string if decoding fails
Example:
`typescript`
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.
`typescript`
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:
`typescript`
base64Decode('aGVsbG8=') // returns 'hello'
base64Decode('eyJmb28iOiJiYXIifQ==') // returns { foo: 'bar' }
`typescript`
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:
`typescript`
base64Encode('hello') // returns 'aGVsbG8='
base64Encode({ foo: 'bar' }) // returns 'eyJmb28iOiJiYXIifQ=='
`typescript`
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:
`typescript`
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.
`typescript`
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:
`typescript`
btoa('Hello World') // returns 'SGVsbG8gV29ybGQ='
btoa('test') // returns 'dGVzdA=='
Remarks: This function is for Node.js environments only. Returns empty string in browser environments.
> Deprecated: Use findById() instead for better naming clarity
`typescript`
byId(items: any[], id: string): void
Finds an item by its id property
Parameters:
- items any - - A collection of objectsid
- any - - The unique identifier on which to match against the 'id' field
Returns: - The first item with matching id, or undefined
Example:
`typescript`
const items = [{ id: '1', name: 'Alice' }, { id: '2', name: 'Bob' }]
byId(items, '2') // returns { id: '2', name: 'Bob' }
`typescript`
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:
`typescript`
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.
`typescript`
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:
`typescript
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
`typescript`
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:
`typescript`
capitalize('hello') // returns 'Hello'
capitalize('world') // returns 'World'
capitalize('123abc') // returns '123abc'
`typescript`
caseInsensitiveCompare(str1: string, str2: string): boolean
Compares two strings case-insensitively
Parameters:
- str1 any - - First string to comparestr2
- any - - Second string to compare
Returns: - True if strings are equal ignoring case, false otherwise
Example:
`typescript`
caseInsensitiveCompare('Hello', 'hello') // returns true
caseInsensitiveCompare('ABC', 'abc') // returns true
caseInsensitiveCompare('foo', 'bar') // returns false
`typescript`
caseInsensitiveIncludes(str: string, arr?: string[]): boolean
Checks if an array contains a string (case-insensitive)
Parameters:
- str any - - The string to search forarr
- any - - The array to search in
Returns: - True if the string is found in the array (case-insensitive), false otherwise
Example:
`typescript`
caseInsensitiveIncludes('HELLO', ['hello', 'world']) // returns true
caseInsensitiveIncludes('foo', ['bar', 'baz']) // returns false
caseInsensitiveIncludes('Test', ['test', 'TEST', 'TeSt']) // returns true
`typescript`
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 processsize
- any - - The length of each chunk
Returns: - Returns the new array containing chunks
Example:
`typescript`
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
`typescript`
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:
`typescript`
clean('Hello "World"') // returns 'Hello \\"World\\"'
clean('') // 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
`typescript`
cleanObject(obj: Record
Recursively removes null, undefined, and empty string values from an object
Parameters:
- obj any - - The object to clean
Returns: - The cleaned object
Example:
`typescript
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
`typescript`
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:
`typescript`
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.
`typescript`
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 arrayb
- any - - Second arrayc
- any - - Third arrayd
- any - - Fourth arraye
- any - - Fifth arrayf
- any - - Sixth arrayg
- any - - Seventh arrayh
- any - - Eighth arrayi
- any - - Ninth array
Returns: - A new array containing all elements from the input arrays
`typescript`
contains(array: any[], x: any): void
Checks if an array contains a specific value
Parameters:
- array any - - The array to searchx
- any - - The value to search for
Returns: - True if the value is found, false otherwise
`typescript`
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 -
> 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
`typescript`
createGroups(arr: any[], groupSize?: any): void
Parameters:
- arr any - groupSize
- any -
`typescript`
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
`typescript`
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:
`typescript`
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
`typescript`
difference(array1: any[], array2: any[]): any[]
Returns the difference between two arrays
Parameters:
- array1 any - - The array to compare fromarray2
- any - - The array to compare against
Returns: - An array of items that are in array1 but not in array2
Example:
`typescript`
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.
`typescript`
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:
`typescript`
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
`typescript`
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 testpredicate
- any - - The function to test each element
Returns: - True if all elements pass the test, false otherwise
`typescript`
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
`typescript`
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 objectsprop
- any - = The name of the property to matchvalue
- any - - The value on which to match against the provided property name
Returns: - The first item in the collection that matches the given id
`typescript`
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 objectsid
- any - - The unique identifier on which to match against the 'id' property
Returns: - The first item in the collection that matches the given id
`typescript`
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 floatlocale
- 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:
`typescript`
formatCurrency(1234.56) // returns "$1,234.56"
formatCurrency(1234.56, 'de-DE', 'EUR') // returns "1.234,56 €"
`typescript`
formatDate(input: any, formatTemplate?: string): string
Formats a date using the Intl.DateTimeFormat API
Parameters:
- input any - - The date to formatformatTemplate
- 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:
`typescript`
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"
`typescript`
formatPercentage(num: number, precision?: number): string
`typescript`
formatPrice(num: number, precision?: number): void
Formats a number as a price string
Parameters:
- num any - - The number to format as floatprecision
- any - - The number of decimal places to include (default: 0)
Returns: - A formatted price string in the specified locale and currency
Example:
`typescript`
formatPrice(1234.56) // returns "$1,234.56"
formatPrice(1234.56, 2) // returns "$1,234.56"
formatPrice(1234.56, 0) // returns "$1,234"
`typescript`
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
`typescript`
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
`typescript`
generateKey(length?: any): void
Generates a random alphanumeric key
Parameters:
- length any - - The length of the key (default: 5)
Returns: - A random alphanumeric string
`typescript`
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:
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
groupBy(collection: any[], property?: string): void
Groups an array of objects by a specified property
Parameters:
- collection any - - The array of objects to groupproperty
- any - - The property name to group by
Returns: - An object with grouped items, keyed by the property value
Example:
`typescript
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 }] }
`
`typescript`
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
`typescript`
hasLength(items?: any[], min?: number): boolean
Checks if an array has a minimum number of elements
Parameters:
- items any - - The array to checkmin
- any - - The minimum number of elements (default: 1)
Returns: - True if the array has at least the minimum number of elements
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
id(): void
Generates a unique ID using UUID v4
Returns: - A UUID string
`typescript`
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
`typescript`
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
`typescript`
includes(items?: any[], value: any): void
Checks if an array includes a specific value
Parameters:
- items any - - The array to searchvalue
- any - - The value to search for
Returns: - True if the value is found, false otherwise
`typescript`
intersect(arr1: any, arr2: any): void
Returns the intersection of two arrays
Parameters:
- arr1 any - arr2
- any -
`typescript`
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
`typescript`
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)
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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 compareother
- any - - The other value to compare
Returns: - True if the values are equivalent, false otherwise
Example:
`typescript
var object = { 'user': 'fred' };
var other = { 'user': 'fred' };
isEqual(object, other);
// => true
object === other;
// => false
`
`typescript`
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
`typescript`
isExpired(expiresOn: string | Date, ttl?: any): void
Checks if a date has expired (is in the past)
Parameters:
- expiresOn any - - The expiration datettl
- any - - Optional time-to-live to add to the expiration date
Returns: - True if the date has expired
`typescript`
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
`typescript`
isInTime(date: any, ttl?: any): void
Checks if a date is within a specified time range from now
Parameters:
- date any - - The date to checkttl
- any - - Time-to-live object specifying the range
Returns: - True if the date is within the specified time range
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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 checkttl
- any - - Optional time period to add to current time for comparison
Returns: - True if the date is older than the comparison time
`typescript`
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
`typescript`
joinWithAnd(array: string[]): void
Joins an array of strings with commas and 'and' for the last item
Parameters:
- array any -
`typescript`
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
`typescript`
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
`typescript`
maxValue(arr: number[]): void
Finds the maximum value in an array of numbers
Parameters:
- arr any - - Array of numbers
Returns: - The maximum value
`typescript`
merge(list?: any[], updates?: any[], prop?: string): void
Merges updates into a list based on a matching property
Parameters:
- list any - - The list to updateupdates
- any - - Array of updates to applyprop
- any - - Property name to match on (default: 'id')
Returns: - The updated list
`typescript`
minValue(arr: number[]): void
Finds the minimum value in an array of numbers
Parameters:
- arr any - - Array of numbers
Returns: - The minimum value
`typescript`
now(): void
Returns the current date and time
Returns: - A new Date object representing the current time
`typescript`
omit(obj: T | null | undefined, keys: string[] | string, additionalKeys?: string[]): Partial
Returns a new object with all keys except the specified keys (opposite of pick)
Parameters:
- obj any - - The source objectkeys
- any - - Array of keys or individual key arguments to omitadditionalKeys
- any - - Additional keys to omit when using string format
Returns: - A new object without the specified keys
Example:
`typescript
const user = { id: 1, name: 'John', email: 'john@example.com', password: 'secret' }
// Array format
omit(user, ['password']) // returns { id: 1, name: 'John', email: 'john@example.com' }
// 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
`typescript`
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
`typescript`
parseEmail(inputString: string): void
Parses an email string that may include a display name
Parameters:
- inputString any - - Email string in format "Display Name
Returns: - Object with address and optional displayName properties
`typescript`
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
`typescript`
parseFileType(filePath: string): string
Tries to determine a files content type by its extension
Parameters:
- filePath any - - file path or filename
`typescript`
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
`typescript`
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
`typescript`
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:
`typescript`
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
`typescript`
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
`typescript`
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 subtractname
- any - - Time unit ('m', 'min', 'mins', 'h', 'hour', 'hours')
Returns: - A Date object in the past
`typescript`
pick(obj: T, keys: string[] | string, additionalKeys?: string[]): Partial
Returns a new object with only the specified keys
Parameters:
- obj any - - The source objectkeys
- any - - Array of keys or individual key arguments to includeadditionalKeys
- any - - Additional keys when using string format
Returns: - A new object containing only the specified keys
Example:
`typescript
const user = { id: 1, name: 'John', email: 'john@example.com', age: 30 }
// Array format
pick(user, ['name', 'email']) // returns { name: 'John', email: 'john@example.com' }
// Variadic format
pick(user, 'name', 'email') // returns { name: 'John', email: 'john@example.com' }
// 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.
`typescript`
pickWithout(obj: T, keys: string[]): Partial
Returns a new object with all keys except the specified keys
Parameters:
- obj any - keys
- any -
`typescript`
plural(word?: any, count?: any, suffix?: any): void
Returns the plural form of a word based on count
Parameters:
- word any - - The word to pluralizecount
- any - - The count to determine if plural is neededsuffix
- any - - The suffix to add for pluralization (default: 's')
Returns: - The word in singular or plural form
`typescript`
pretty(obj?: any, indent?: any): void
Converts an object to a pretty-printed JSON string
Parameters:
- obj any - - The object to stringifyindent
- any - - Number of spaces for indentation (default: 4)
Returns: - Pretty-printed JSON string
`typescript`
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 toinsert
- any - - The item(s) to insertuniq
- any - - Whether to check for uniqueness (default: true)
Returns: - The modified array
`typescript`
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
`typescript`
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
`typescript`
remove(array?: any[], value: any): void
Removes all instances of a value from an array
Parameters:
- array any - - The array to filtervalue
- any - - The value to remove
Returns: - A new array with the value removed
`typescript`
removeEmptyObjects(collection?: any): void
Removes empty objects from a collection
Parameters:
- collection any - - Array of objects to filter
Returns: - Array with empty objects removed
`typescript`
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
`typescript`
round(num: any, i?: any): void
Rounds a number to specified decimal places
Parameters:
- num any - - The number to roundi
- any - - Number of decimal places (default: 2)
Returns: - The rounded number
`typescript`
some(array: any[], predicate: any): void
Tests whether at least one element passes the provided function
Parameters:
- array any - - The array to testpredicate
- any - - The function to test each element
Returns: - True if at least one element passes the test
`typescript`
sortBy(arr: any[], prop: string, desc?: boolean): void
Sorts an array of objects by a specified property
Parameters:
- arr any - - The array to sortprop
- any - - The property name to sort bydesc
- any - - Whether to sort in descending order (default: false)
Returns: - The sorted array
`typescript`
split(str: string, delimiter?: any): void
Splits a string by delimiter and deduplicates the result
Parameters:
- str any - - The string to splitdelimiter
- any - - The delimiter to split by (default: ',')
Returns: - Array of unique split values or original string if no delimiter found
`typescript`
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
`typescript`
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
`typescript`
stringify(data: any): void
Safely converts data to a string representation
Parameters:
- data any - - The data to stringify
Returns: - String representation of the data
`typescript`
test(str: string, re: any, word?: boolean, flags?: string): void
Tests a string against a regular expression
Parameters:
- str any - - The string to testre
- any - - The regular expression patternword
- 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
`typescript`
titleCase(str: string): string
Converts a string to title case
Parameters:
- str any - - The string to convert
Returns: - The string in title case format
`typescript`
toBoolean(value: any, defaultValue?: any): void
Converts a value to a boolean
Parameters:
- value any - - The value to convertdefaultValue
- any - - Default value if input is null/undefined (default: false)
Returns: - Boolean representation of the value
`typescript`
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 -
`typescript`
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
`typescript`
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
`typescript`
unique(prefix?: any, suffix?: any): void
Creates a unique value based on the current timestamp
Used primarily for testing
Parameters:
- prefix any - suffix
- any -
`typescript`
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
`typescript`
without(array: T[], values?: T[]): T[]
Returns a new array with specified values removed
Parameters:
- array any - - The source arrayvalues
- any - - Values to exclude from the result
Returns: - A new array without the specified values
---
`typescript`
delay(fn: Function, time?: number): void
Executes a function after a delay.
Parameters:
- fn any - - The function to executetime
- any - - Delay duration in milliseconds (default: random 1-10 seconds)
Returns: - The timeout ID for clearing with clearTimeout
`typescript`
interval(fn: Function, time?: number, immediate?: boolean): void
Executes a function at regular intervals.
Parameters:
- fn any - - The function to executetime
- 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
`typescript`
retry(fn: Function, retryWait?: number, maxAttempts?: number): void
Retries a function multiple times with a delay between attempts.
Parameters:
- fn any - - The function to executeretryWait
- 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
---
`typescript`
copyToClipboard(text: string): void
Copies text to the clipboard using the Clipboard API.
Parameters:
- text any - - The text to copy to clipboard
`typescript`
params(name: string, url?: string): void
Extracts a query parameter value from a URL.
Parameters:
- name any - - The name of the query parameterurl
- any - - The URL to parse (default: current window location)
Returns: - The decoded parameter value, or undefined if not found
---
formatRateWindow | getCurrentRateWindow | getRateWindow | isCurrentRateWindow
`typescript`
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")
`typescript`
getCurrentRateWindow(): void
Gets the current rate window (start of the current hour).
Returns: - Date object representing the start of the current hour
`typescript`
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
`typescript`
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
---
$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
`typescript`
$10minutesAgo(): void
`typescript`
$10minutesFromNow(): void
`typescript`
$10secondsAgo(): void
`typescript`
$12hoursAgo(): void
`typescript`
$1dayAgo(): void
`typescript`
$1hourAgo(): void
`typescript`
$1hourFromNow(): void
`typescript`
$1minuteAgo(): void
`typescript`
$1minuteFromNow(): void
`typescript`
$1monthAgo(): void
`typescript`
$1secondAgo(): void
`typescript`
$1secondFromNow(): void
`typescript`
$1weekAgo(): void
`typescript`
$1weekFromNow(): void
`typescript`
$1yearAgo(): void
`typescript`
$24HoursAgo(): void
`typescript`
$2daysAgo(): void
`typescript`
$2daysFromNow(): void
`typescript`
$2hoursAgo(): void
`typescript`
$2minutesAgo(): void
`typescript`
$2monthsAgo(): void
`typescript`
$2secondsAgo(): void
`typescript`
$2weeksAgo(): void
`typescript`
$2weeksFromNow(): void
`typescript`
$30daysAgo(): void
`typescript`
$30minutesAgo(): void
`typescript`
$30secondsAgo(): void
`typescript`
$3daysFromNow(): void
`typescript`
$3hoursAgo(): void
`typescript`
$3minutesAgo(): void
`typescript`
$3monthsAgo(): void
`typescript`
$3monthsFromNow(): void
`typescript`
$3secondsAgo(): void
`typescript`
$45secondsAgo(): void
`typescript`
$4minutesAgo(): void
`typescript`
$4monthsAgo(): void
`typescript`
$4secondsAgo(): void
`typescript`
$5minutesAgo(): void
`typescript`
$5monthsAgo(): void
`typescript`
$5secondsAgo(): void
`typescript`
$6hoursAgo(): void
`typescript`
$6monthsAgo(): void
`typescript`
$6monthsFromNow(): void
`typescript`
$daysFromNow(days: number): void
`typescript`
$lastWeek(): void
`typescript`
$nextMonth(): void
`typescript`
$nextWeek(): void
`typescript`
$nextYear(): void
`typescript`
$today(): void
`typescript`
$tomorrow(): void
`typescript`
$yesterday(): void
`typescript`
last12hours(): void
`typescript`
last24hours(): void
`typescript`
last30minutes(): void
---
addToDay | fromDay | getDayOfWeek | getDaysOfWeek | isDayFormat | lastWeek | lastYear | nextDay | nextWeek | today | toDay | tomorrow | yesterday
`typescript`
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 formatdays
- number - - Number of days to add (can be negative to subtract)
Returns: string - The resulting date in YYYY-MM-DD format
`typescript`
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 formattimezone
- 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
`typescript`
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
`typescript`
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 formatendDay
- string - - End date in YYYY-MM-DD format (inclusive)
Returns: dayOfWeek[] - Array of unique day names as lowercase strings
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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
`typescript`
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