@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/utilsUsage
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): voidAdds time intervals to a date
Parameters:
dateany- - The date to add time to (string or Date object)timeany- - 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[]): voidChecks if all strings in the array are valid IDs (32 characters long)
Parameters:
idsany- - 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 falsearraysContainSameValues
arraysContainSameValues(arr1?: any[], arr2?: any[]): booleanChecks if two arrays contain the same values regardless of order
Parameters:
arr1any- - First array to comparearr2any- - 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 trueRemarks: 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): voidDecodes a base64 encoded string
Parameters:
dataany- - The base64 encoded data to decodeencodingany- - 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): voidDecodes a base64 string back to its original value
Parameters:
base64Strany- - 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): voidEncodes a string or object to base64 format
Parameters:
inputany- - 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): voidExtracts the filename without extension from a file path
Parameters:
uriany- - 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 undefinedRemarks: Handles both forward slashes (/) and backslashes () as path separators.
btoa
btoa(data: any): voidEncodes data to base64
Parameters:
dataany- - 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): voidFinds an item by its id property
Parameters:
itemsany- - A collection of objectsidany- - 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): stringConverts a string to camelCase format
Parameters:
strany- - 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): anyRecursively converts object keys from snake_case to camelCase
Parameters:
objany- - 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): voidCapitalizes the first letter of a string
Parameters:
strany- - 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): booleanCompares two strings case-insensitively
Parameters:
str1any- - First string to comparestr2any- - 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 falsecaseInsensitiveIncludes
caseInsensitiveIncludes(str: string, arr?: string[]): booleanChecks if an array contains a string (case-insensitive)
Parameters:
strany- - The string to search forarrany- - 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 truechunk
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:
arrayany- - The array to processsizeany- - 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): voidCleans a string by escaping quotes and replacing angle brackets
Parameters:
valany- - 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:
objany- - 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): voidCreates a shallow copy of a value
Parameters:
valueany- - 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 42Remarks: 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[]): voidConcatenates multiple arrays into a single array
Parameters:
aany- - First arraybany- - Second arraycany- - Third arraydany- - Fourth arrayeany- - Fifth arrayfany- - Sixth arraygany- - Seventh arrayhany- - Eighth arrayiany- - Ninth array
Returns: - A new array containing all elements from the input arrays
contains
contains(array: any[], x: any): voidChecks if an array contains a specific value
Parameters:
arrayany- - The array to searchxany- - The value to search for
Returns: - True if the value is found, false otherwise
createGatewayEvent
createGatewayEvent(body?: any, params?: any): voidCreates a json object in the format used by AWS Gateway events Used primarily for testing
Parameters:
bodyany-paramsany-
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): voidParameters:
arrany-groupSizeany-
createSnsEvent
createSnsEvent(message: any): voidCreates a mock SNS event object for testing
Parameters:
messageany- - The message to include in the SNS event
Returns: - A mock SNS event object
deduplicate
deduplicate(array: any[]): voidRemoves duplicate values from the given array
Parameters:
arrayany- - 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:
array1any- - The array to compare fromarray2any- - 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:
arrayany- - 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): voidTests whether all elements in the array pass the test implemented by the provided function
Parameters:
itemsany- - The array to testpredicateany- - The function to test each element
Returns: - True if all elements pass the test, false otherwise
extension
extension(filename: string): voidParses the file extension from the given filename, including the '.'
Parameters:
filenameany-
Returns: - The file extension of the given filename
findBy
findBy(items: any[], prop: string, value: any): voidFinds the first item in a collection of objects that matches the given id
Parameters:
itemsany- - A collection of objectspropany- = The name of the property to matchvalueany- - 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): voidFinds the first item in a collection of objects that matches the given id
Parameters:
itemsany- - A collection of objectsidany- - 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): voidFormats a number as a currency string using the Intl.NumberFormat API
Parameters:
amountany- - The number to format as floatlocaleany- - The locale to use for formatting (default: 'en-US')currencyany- - 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): stringFormats a date using the Intl.DateTimeFormat API
Parameters:
inputany- - The date to formatformatTemplateany- - 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): stringformatPrice
formatPrice(num: number, precision?: number): voidFormats a number as a price string
Parameters:
numany- - The number to format as floatprecisionany- - 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): stringGenerates a random numeric code with the specified number of digits
Parameters:
numDigitsany- - The number of digits in the code (default: 6)
Returns: - A random numeric code as a string
generateId
generateId(iterations?: any): voidGenerates a unique ID by concatenating UUIDs
Parameters:
iterationsany- - The number of UUIDs to concatenate (default: 1)
Returns: - A unique ID string
generateKey
generateKey(length?: any): voidGenerates a random alphanumeric key
Parameters:
lengthany- - The length of the key (default: 5)
Returns: - A random alphanumeric string
generateUuid
generateUuid(separator?: any): stringGenerates a RFC 4122 compliant UUID v4
Parameters:
separatorany- - 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): voidDetermines the credit card type based on the card number
Parameters:
cardNumberany- - The credit card number to analyze
Returns: - The card type (VISA, MASTERCARD, AMEX, DISCOVER, JCB, DINERSCLUB) or undefined
getCurrencySymbol
getCurrencySymbol(currencyCode: string): voidGets the currency symbol for a given currency code
Parameters:
currencyCodeany- - The ISO currency code (e.g., 'USD', 'EUR')
Returns: - The currency symbol or '$' as fallback
groupBy
groupBy(collection: any[], property?: string): voidGroups an array of objects by a specified property
Parameters:
collectionany- - The array of objects to grouppropertyany- - 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[]): voidChecks if an array has any elements
Parameters:
itemsany- - The array to check
Returns: - True if the array has elements, false otherwise
hasLength
hasLength(items?: any[], min?: number): booleanChecks if an array has a minimum number of elements
Parameters:
itemsany- - The array to checkminany- - The minimum number of elements (default: 1)
Returns: - True if the array has at least the minimum number of elements
hasMany
hasMany(items: any[]): voidChecks if an array has more than one element
Parameters:
itemsany- - The array to check
Returns: - True if the array has 2 or more elements
hasNone
hasNone(items?: any[]): voidChecks if an array has no elements
Parameters:
itemsany- - The array to check
Returns: - True if the array is empty or null/undefined
hasOne
hasOne(items?: any[]): voidChecks if an array has exactly one element
Parameters:
itemsany- - The array to check
Returns: - True if the array has exactly one element
id
id(): voidGenerates a unique ID using UUID v4
Returns: - A UUID string
ids
ids(items?: any[]): voidExtracts and deduplicates IDs from an array of objects
Parameters:
itemsany- - Array of objects with id properties
Returns: - Array of unique IDs
ignoreCase
ignoreCase(value: string): voidCreates a case-insensitive regular expression for exact matching
Parameters:
valueany- - The string to create a regex for
Returns: - A case-insensitive RegExp object
includes
includes(items?: any[], value: any): voidChecks if an array includes a specific value
Parameters:
itemsany- - The array to searchvalueany- - The value to search for
Returns: - True if the value is found, false otherwise
intersect
intersect(arr1: any, arr2: any): voidReturns the intersection of two arrays
Parameters:
arr1any-arr2any-
isArray
isArray(value: any): voidChecks if a value is an array
Parameters:
valueany- - The value to check
Returns: - True if the value is an array
isBoolean
isBoolean(value: string): voidChecks if a string represents a boolean value
Parameters:
valueany- - The string to check
Returns: - True if the string is 'true' or 'false' (case-insensitive)
isBuffer
isBuffer(value: any): voidChecks if a value is a Buffer
Parameters:
valueany- - The value to check
Returns: - True if the value is a Buffer
isDate
isDate(input: any): booleanChecks if a value is a valid date or date string
Parameters:
inputany- - The value to check
Returns: - True if the value is a valid date
isEmail
isEmail(email: string): voidChecks if a string is a valid email address
Parameters:
emailany- - The string to check
Returns: - True if the string is a valid email format
isEmptyObject
isEmptyObject(obj?: any): voidChecks if an object is empty (has no own properties)
Parameters:
objany- - The object to check
Returns: - True if the object is empty or falsy
isEqual
isEqual(value: any, other: any): booleanPerforms 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:
valueany- - The value to compareotherany- - 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;
// => falseisError
isError(value: any): voidChecks if a value is an Error object
Parameters:
valueany- - The value to check
Returns: - True if the value is an Error instance
isExpired
isExpired(expiresOn: string | Date, ttl?: any): voidChecks if a date has expired (is in the past)
Parameters:
expiresOnany- - The expiration datettlany- - Optional time-to-live to add to the expiration date
Returns: - True if the date has expired
isId
isId(id?: string): booleanChecks if a string is a valid ID (32 characters long)
Parameters:
idany- - The string to check
Returns: - True if the string is a valid ID
isInTime
isInTime(date: any, ttl?: any): voidChecks if a date is within a specified time range from now
Parameters:
dateany- - The date to checkttlany- - Time-to-live object specifying the range
Returns: - True if the date is within the specified time range
isJson
isJson(value: string): voidChecks if a string is valid JSON
Parameters:
valueany- - The string to check
Returns: - True if the string is valid JSON
isNullOrUndefined
isNullOrUndefined(value: any): voidChecks if a value is null or undefined
Parameters:
valueany- - The value to check
Returns: - True if the value is null or undefined
isNumber
isNumber(value: any): voidChecks if a value is a valid number
Parameters:
valueany- - The value to check
Returns: - True if the value is a finite number
isObject
isObject(input: any): booleanChecks if a value is an object (not array, null, or primitive)
Parameters:
inputany- - The value to check
Returns: - True if the value is an object
isOlderThan
isOlderThan(date: any, ttl?: any): voidChecks if a date is older than a specified time period or current time
Parameters:
dateany- - The date to checkttlany- - 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): booleanChecks if a value is a string
Parameters:
inputany- - The value to check
Returns: - True if the value is a string
joinWithAnd
joinWithAnd(array: string[]): voidJoins an array of strings with commas and 'and' for the last item
Parameters:
arrayany-
key
key(length?: any): voidGenerates a random alphanumeric key (alias for generateKey)
Parameters:
lengthany- - The length of the key (default: 5)
Returns: - A random alphanumeric string
keyify
keyify(value: string): stringConverts a string to a URL-friendly key format
Parameters:
valueany- - The string to convert
Returns: - A URL-friendly string with lowercase letters, numbers, and hyphens
maxValue
maxValue(arr: number[]): voidFinds the maximum value in an array of numbers
Parameters:
arrany- - Array of numbers
Returns: - The maximum value
merge
merge(list?: any[], updates?: any[], prop?: string): voidMerges updates into a list based on a matching property
Parameters:
listany- - The list to updateupdatesany- - Array of updates to applypropany- - Property name to match on (default: 'id')
Returns: - The updated list
minValue
minValue(arr: number[]): voidFinds the minimum value in an array of numbers
Parameters:
arrany- - Array of numbers
Returns: - The minimum value
now
now(): voidReturns 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:
objany- - The source objectkeysany- - Array of keys or individual key arguments to omitadditionalKeysany- - 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): voidGenerates a random order number using alphanumeric characters
Parameters:
lenany- - The length of the order number (default: 8)
Returns: - A random order number string
parseEmail
parseEmail(inputString: string): voidParses an email string that may include a display name
Parameters:
inputStringany- - Email string in format "Display Name [email protected]" or "[email protected]"
Returns: - Object with address and optional displayName properties
parseErrorMessage
parseErrorMessage(err: any): voidExtracts an error message from various error formats
Parameters:
errany- - The error object, string, or data structure
Returns: - The error message string or undefined
parseFileType
parseFileType(filePath: string): stringTries to determine a files content type by its extension
Parameters:
filePathany- - file path or filename
parseFullName
parseFullName(fullName: string): { firstName: string; lastName: string }Parses a full name into first and last name components
Parameters:
fullNameany- - The full name string to parse
Returns: - Object with firstName and lastName properties
parseGatewayMessage
parseGatewayMessage(event?: any): voidParses an AWS API Gateway event into a structured message
Parameters:
eventany- - The API Gateway event object
Returns: - Object with parsed body, headers, and params
parseJSON
parseJSON(input: any): voidSafely parses JSON, returning the original input if parsing fails
Parameters:
inputany- - 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): voidParses an AWS SNS message from an event
Parameters:
eventany- - The SNS event object
Returns: - The parsed message or empty object if parsing fails
past
past(num: number, name?: any): voidCreates a date in the past by subtracting time from now
Parameters:
numany- - Number of time units to subtractnameany- - 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:
objany- - The source objectkeysany- - Array of keys or individual key arguments to includeadditionalKeysany- - 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:
objany-keysany-
plural
plural(word?: any, count?: any, suffix?: any): voidReturns the plural form of a word based on count
Parameters:
wordany- - The word to pluralizecountany- - The count to determine if plural is neededsuffixany- - The suffix to add for pluralization (default: 's')
Returns: - The word in singular or plural form
pretty
pretty(obj?: any, indent?: any): voidConverts an object to a pretty-printed JSON string
Parameters:
objany- - The object to stringifyindentany- - Number of spaces for indentation (default: 4)
Returns: - Pretty-printed JSON string
push
push(array?: any[], insert: any, uniq?: boolean): voidPushes one or more items to an array with optional uniqueness check
Parameters:
arrayany- - The array to push toinsertany- - The item(s) to insertuniqany- - Whether to check for uniqueness (default: true)
Returns: - The modified array
random
random(max?: number): voidGenerates a random integer between 0 and max (exclusive)
Parameters:
maxany- - The maximum value (exclusive, default: 100)
Returns: - A random integer
randomInRange
randomInRange(min: number, max: number): numberGenerates a random integer within a specified range (inclusive)
Parameters:
minany- - The minimum value (inclusive)maxany- - The maximum value (inclusive)
Returns: - A random integer within the range
remove
remove(array?: any[], value: any): voidRemoves all instances of a value from an array
Parameters:
arrayany- - The array to filtervalueany- - The value to remove
Returns: - A new array with the value removed
removeEmptyObjects
removeEmptyObjects(collection?: any): voidRemoves empty objects from a collection
Parameters:
collectionany- - Array of objects to filter
Returns: - Array with empty objects removed
removeEmptyProperties
removeEmptyProperties(obj: any): voidRemoves empty properties (null, undefined, empty string) from an object
Parameters:
objany- - The object to clean
Returns: - A new object with empty properties removed
round
round(num: any, i?: any): voidRounds a number to specified decimal places
Parameters:
numany- - The number to roundiany- - Number of decimal places (default: 2)
Returns: - The rounded number
some
some(array: any[], predicate: any): voidTests whether at least one element passes the provided function
Parameters:
arrayany- - The array to testpredicateany- - The function to test each element
Returns: - True if at least one element passes the test
sortBy
sortBy(arr: any[], prop: string, desc?: boolean): voidSorts an array of objects by a specified property
Parameters:
arrany- - The array to sortpropany- - The property name to sort bydescany- - Whether to sort in descending order (default: false)
Returns: - The sorted array
split
split(str: string, delimiter?: any): voidSplits a string by delimiter and deduplicates the result
Parameters:
strany- - The string to splitdelimiterany- - 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:
emailListany- - 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:
fullNameany- - The full name string to split
Returns: - Object with firstName and lastName properties
stringify
stringify(data: any): voidSafely converts data to a string representation
Parameters:
dataany- - The data to stringify
Returns: - String representation of the data
test
test(str: string, re: any, word?: boolean, flags?: string): voidTests a string against a regular expression
Parameters:
strany- - The string to testreany- - The regular expression patternwordany- - Whether to match whole word only (default: false)flagsany- - RegExp flags (default: 'i' for case-insensitive)
Returns: - True if the string matches the pattern
titleCase
titleCase(str: string): stringConverts a string to title case
Parameters:
strany- - The string to convert
Returns: - The string in title case format
toBoolean
toBoolean(value: any, defaultValue?: any): voidConverts a value to a boolean
Parameters:
valueany- - The value to convertdefaultValueany- - Default value if input is null/undefined (default: false)
Returns: - Boolean representation of the value
toHash
toHash(array: any[], keyProperty?: any, valueProperty?: string): voidCreates a new object from the given collection of objects, using the value of given property as the hash key
Parameters:
arrayany-keyPropertyany-valuePropertyany-
toPrice
toPrice(price: number | string, def?: number): numberEnsures the proper formatting of a currency value
Parameters:
priceany-defany- - default value if the price is not a valid number
toSnakeCase
toSnakeCase(obj: any): anyRecursively converts object keys from camelCase to snake_case
Parameters:
objany- - The object to convert
Returns: - Object with snake_case keys
unique
unique(prefix?: any, suffix?: any): voidCreates a unique value based on the current timestamp Used primarily for testing
Parameters:
prefixany-suffixany-
wait
wait(ms: number): voidWaits for the specified number of milliseconds
Parameters:
msany- - 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:
arrayany- - The source arrayvaluesany- - Values to exclude from the result
Returns: - A new array without the specified values
functions
delay
delay(fn: Function, time?: number): voidExecutes a function after a delay.
Parameters:
fnany- - The function to executetimeany- - 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): voidExecutes a function at regular intervals.
Parameters:
fnany- - The function to executetimeany- - Interval duration in milliseconds (default: 5 minutes)immediateany- - 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): voidRetries a function multiple times with a delay between attempts.
Parameters:
fnany- - The function to executeretryWaitany- - Milliseconds to wait between retries (default: random 4-6 seconds)maxAttemptsany- - Maximum number of attempts (default: 3)
Returns: - The result of the function if successful
html
copyToClipboard
copyToClipboard(text: string): voidCopies text to the clipboard using the Clipboard API.
Parameters:
textany- - The text to copy to clipboard
params
params(name: string, url?: string): voidExtracts a query parameter value from a URL.
Parameters:
nameany- - The name of the query parameterurlany- - 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): voidFormats a date as a rate window string.
Parameters:
dateany- - The date to format
Returns: - Formatted string (e.g., "Jan, 1st 2:00 pm")
getCurrentRateWindow
getCurrentRateWindow(): voidGets the current rate window (start of the current hour).
Returns: - Date object representing the start of the current hour
getRateWindow
getRateWindow(date: any): voidGets the rate window for a given date (start of that hour).
Parameters:
dateany- - The date to get the rate window for
Returns: - Date object representing the start of that hour
isCurrentRateWindow
isCurrentRateWindow(date: string | Date): voidChecks if a date falls within the current rate window (same hour).
Parameters:
dateany- - 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(): voidlast12hours
last12hours(): voidlast24hours
last24hours(): voidlast30minutes
last30minutes(): voidday
addToDay | fromDay | getDayOfWeek | getDaysOfWeek | isDayFormat | lastWeek | lastYear | nextDay | nextWeek | today | toDay | tomorrow | yesterday
addToDay
addToDay(yyyymmdd: string, days: number): stringAdds the specified number of days to the given date string.
Parameters:
yyyymmddstring- - The date string in YYYY-MM-DD formatdaysnumber- - 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): DateConverts 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:
dayany- - Date string in YYYY-MM-DD formattimezoneany- - 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): dayOfWeekGets the day of the week for a given date string.
Parameters:
dateStringstring- - 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:
startDaystring- - Start date in YYYY-MM-DD formatendDaystring- - End date in YYYY-MM-DD format (inclusive)
Returns: dayOfWeek[] - Array of unique day names as lowercase strings
isDayFormat
isDayFormat(yyyymmdd: string): voidValidates if a string matches the YYYY-MM-DD date format and represents a valid date
Parameters:
yyyymmddany- - 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): stringReturns the date one week ago from today as a string in YYYY-MM-DD format.
Parameters:
timezonestring- - 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): stringReturns the date one year ago from today as a string in YYYY-MM-DD format.
Parameters:
timezonestring- - 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): stringReturns the next day for a given date string.
Parameters:
yyyymmddstring- - The date string in YYYY-MM-DD format
Returns: string - The next day in YYYY-MM-DD format
nextWeek
nextWeek(timezone?: string): stringReturns the date one week from today as a string in YYYY-MM-DD format.
Parameters:
timezonestring- - 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): stringReturns today's date as a string in YYYY-MM-DD format.
Parameters:
timezonestring- - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')
Returns: string - Today's date in YYYY-MM-DD format
toDay
toDay(date?: Date): stringConverts a Date object to a string in YYYY-MM-DD format.
Parameters:
dateDate- - The date to convert. Defaults to current date if not provided.
Returns: string - The date in YYYY-MM-DD format
tomorrow
tomorrow(timezone?: string): stringReturns tomorrow's date as a string in YYYY-MM-DD format.
Parameters:
timezonestring- - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')
Returns: string - Tomorrow's date in YYYY-MM-DD format
yesterday
yesterday(timezone?: string): stringReturns yesterday's date as a string in YYYY-MM-DD format.
Parameters:
timezonestring- - Optional IANA timezone identifier (e.g., 'America/New_York', 'UTC')
Returns: string - Yesterday's date in YYYY-MM-DD format
