@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 | parseName | parseSnsMessage | past | pick | pickWithout | plural | pretty | push | random | randomInRange | remove | removeEmptyObjects | removeEmptyProperties | round | some | sortBy | split | splitEmails | splitFullName | stringify | test | titleCase | toBoolean | toCamelCase | toFullName | 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:
addDate(new Date(), { hours: 2 })
addDate('2024-01-01', { days: 5, hours: 3, minutes: 30 })
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)])
areIds(['short', 'ids'])
areIds(['a'.repeat(32), 'invalid'])
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])
arraysContainSameValues([1, 2], [1, 2, 3])
arraysContainSameValues([], [])
arraysContainSameValues(undefined, undefined)
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=')
atob('SGVsbG8=', 'utf-8')
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=')
base64Decode('eyJmb28iOiJiYXIifQ==')
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')
base64Encode({ foo: 'bar' })
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')
basename('C:\\Users\\file.doc')
basename('document.pdf')
basename('/path/to/folder/')
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')
btoa('test')
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')
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')
camelCase('foo-bar-baz')
camelCase('user_name')
camelCase('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' })
camelCaseKeys({ user_info: { user_name: 'john' } })
camelCaseKeys([{ user_id: 1 }, { user_id: 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')
capitalize('world')
capitalize('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')
caseInsensitiveCompare('ABC', 'abc')
caseInsensitiveCompare('foo', 'bar')
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'])
caseInsensitiveIncludes('foo', ['bar', 'baz'])
caseInsensitiveIncludes('Test', ['test', 'TEST', 'TeSt'])
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)
chunk(['a', 'b', 'c', 'd'], 3)
chunk([1, 2, 3, 4, 5, 6])
chunk([], 5)
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"')
clean('<script>alert()</script>')
clean('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: '' })
cleanObject({ user: { name: 'John', email: null }, items: ['a', '', 'b'] })
cleanObject({ empty: {}, data: { value: null } })
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 })
clone([1, 2, 3])
clone('string')
clone(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:
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])
deduplicate(['a', 'b', 'a', 'c'])
deduplicate([1, null, 2, undefined, 3])
deduplicate([true, false, 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])
difference(['a', 'b', 'c'], ['b'])
difference([1, 2], [3, 4])
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)
ensureArray([1, 2, 3])
ensureArray('hello')
ensureArray(null)
ensureArray(undefined)
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:
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)
formatCurrency(1234.56, 'de-DE', 'EUR')
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())
formatDate(new Date(), 'MM/dd/yyyy')
formatDate(new Date(), 'MM/dd/yyyy h:mm a z')
formatDate(new Date(), 'timestamp')
formatDate(new Date(), 'relative')
formatDate(new Date(), 'short')
formatDate(new Date(), 'friendly')
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)
formatPrice(1234.56, 2)
formatPrice(1234.56, 0)
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()
generateUuid('-')
generateUuid('_')
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')
const items = [{ category: 'A', value: 1 }, { category: 'B', value: 2 }, { category: 'A', value: 3 }]
groupBy(items, 'category')
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:
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);
object === other;
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:
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: 'john@example.com', password: 'secret' }
omit(user, ['password'])
omit(user, 'password', 'email')
omit(null, ['key'])
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"}')
parseJSON('[1,2,3]')
parseJSON('invalid json')
parseJSON(null)
parseJSON({ already: 'parsed' })
Remarks: - Returns input unchanged if null, undefined, or not a string
- Returns input if JSON parsing fails
- Never throws errors
parseName
parseName(fullName: string): { firstName: string; middleName: string; lastName: string }
Parses a full name string into its component parts
Parameters:
fullName any - - The full name string to parse
Returns: - Object with firstName, middleName, and lastName properties
Example:
parseName('John Robert Doe')
parseName('Jane Smith')
parseName('Bob')
parseName('Mary Jane Watson Parker')
Remarks: - Single word names are treated as firstName
- Two word names are split into firstName and lastName
- Three or more words: first word is firstName, last word is lastName, everything in between is middleName
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: 'john@example.com', age: 30 }
pick(user, ['name', 'email'])
pick(user, 'name', 'email')
pick(user, ['name', 'nonexistent'])
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:
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
Deprecated: Use parseFullName instead
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
toCamelCase
toCamelCase(value: string): string
Converts a string to camelCase format
Parameters:
value any - - The string to convert
Returns: - The string in camelCase format
Example:
toCamelCase('hello_world')
toCamelCase('foo-bar-baz')
toCamelCase('Hello World')
toCamelCase('PascalCase')
Remarks: Handles various input formats including snake_case, kebab-case, and space-separated words.
Ensures the first character is lowercase.
toFullName
toFullName(name: { firstName?: string; middleName?: string; lastName?: string }): string
Combines name parts into a full name string
Parameters:
name any - - Object containing firstName, middleName, and lastName
Returns: - The combined full name with proper spacing
Example:
toFullName({ firstName: 'John', middleName: 'Robert', lastName: 'Doe' })
toFullName({ firstName: 'Jane', middleName: '', lastName: 'Smith' })
toFullName({ firstName: 'Bob', middleName: undefined, lastName: '' })
Remarks: - Handles missing or empty name parts gracefully
- Trims extra whitespace from the result
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 | $10secondsFromNow | $12hoursAgo | $12hoursFromNow | $14daysAgo | $14daysFromNow | $15minutesAgo | $15minutesFromNow | $15secondsAgo | $1dayAgo | $1hourAgo | $1hourFromNow | $1minuteAgo | $1minuteFromNow | $1monthAgo | $1monthFromNow | $1secondAgo | $1secondFromNow | $1weekAgo | $1weekFromNow | $1yearAgo | $1yearFromNow | $20minutesAgo | $20secondsAgo | $24hoursAgo | $24hoursFromNow | $2daysAgo | $2daysFromNow | $2hoursAgo | $2hoursFromNow | $2minutesAgo | $2monthsAgo | $2monthsFromNow | $2secondsAgo | $2weeksAgo | $2weeksFromNow | $30daysAgo | $30daysFromNow | $30minutesAgo | $30minutesFromNow | $30secondsAgo | $30secondsFromNow | $3daysAgo | $3daysFromNow | $3hoursAgo | $3hoursFromNow | $3minutesAgo | $3monthsAgo | $3monthsFromNow | $3secondsAgo | $3weeksAgo | $3weeksFromNow | $45minutesAgo | $45minutesFromNow | $45secondsAgo | $4hoursAgo | $4hoursFromNow | $4minutesAgo | $4monthsAgo | $4monthsFromNow | $4secondsAgo | $4weeksAgo | $4weeksFromNow | $5daysAgo | $5daysFromNow | $5minutesAgo | $5minutesFromNow | $5monthsAgo | $5monthsFromNow | $5secondsAgo | $5secondsFromNow | $6hoursAgo | $6hoursFromNow | $6monthsAgo | $6monthsFromNow | $6secondsAgo | $7daysAgo | $7daysFromNow | $7secondsAgo | $8hoursAgo | $8hoursFromNow | $daysFromNow | $lastWeek | $nextMonth | $nextWeek | $nextYear | $today | $tomorrow | $yesterday | last12hours | last24hours | last30minutes
$10minutesAgo
$10minutesAgo(): void
$10minutesFromNow
$10minutesFromNow(): void
$10secondsAgo
$10secondsAgo(): void
$10secondsFromNow
$10secondsFromNow(): void
$12hoursAgo
$12hoursAgo(): void
$12hoursFromNow
$12hoursFromNow(): void
$14daysAgo
$14daysAgo(): void
$14daysFromNow
$14daysFromNow(): void
$15minutesAgo
$15minutesAgo(): void
$15minutesFromNow
$15minutesFromNow(): void
$15secondsAgo
$15secondsAgo(): void
$1dayAgo
$1dayAgo(): void
$1hourAgo
$1hourAgo(): void
$1hourFromNow
$1hourFromNow(): void
$1minuteAgo
$1minuteAgo(): void
$1minuteFromNow
$1minuteFromNow(): void
$1monthAgo
$1monthAgo(): void
$1monthFromNow
$1monthFromNow(): void
$1secondAgo
$1secondAgo(): void
$1secondFromNow
$1secondFromNow(): void
$1weekAgo
$1weekAgo(): void
$1weekFromNow
$1weekFromNow(): void
$1yearAgo
$1yearAgo(): void
$1yearFromNow
$1yearFromNow(): void
$20minutesAgo
$20minutesAgo(): void
$20secondsAgo
$20secondsAgo(): void
$24hoursAgo
$24hoursAgo(): void
$24hoursFromNow
$24hoursFromNow(): void
$2daysAgo
$2daysAgo(): void
$2daysFromNow
$2daysFromNow(): void
$2hoursAgo
$2hoursAgo(): void
$2hoursFromNow
$2hoursFromNow(): void
$2minutesAgo
$2minutesAgo(): void
$2monthsAgo
$2monthsAgo(): void
$2monthsFromNow
$2monthsFromNow(): void
$2secondsAgo
$2secondsAgo(): void
$2weeksAgo
$2weeksAgo(): void
$2weeksFromNow
$2weeksFromNow(): void
$30daysAgo
$30daysAgo(): void
$30daysFromNow
$30daysFromNow(): void
$30minutesAgo
$30minutesAgo(): void
$30minutesFromNow
$30minutesFromNow(): void
$30secondsAgo
$30secondsAgo(): void
$30secondsFromNow
$30secondsFromNow(): void
$3daysAgo
$3daysAgo(): void
$3daysFromNow
$3daysFromNow(): void
$3hoursAgo
$3hoursAgo(): void
$3hoursFromNow
$3hoursFromNow(): void
$3minutesAgo
$3minutesAgo(): void
$3monthsAgo
$3monthsAgo(): void
$3monthsFromNow
$3monthsFromNow(): void
$3secondsAgo
$3secondsAgo(): void
$3weeksAgo
$3weeksAgo(): void
$3weeksFromNow
$3weeksFromNow(): void
$45minutesAgo
$45minutesAgo(): void
$45minutesFromNow
$45minutesFromNow(): void
$45secondsAgo
$45secondsAgo(): void
$4hoursAgo
$4hoursAgo(): void
$4hoursFromNow
$4hoursFromNow(): void
$4minutesAgo
$4minutesAgo(): void
$4monthsAgo
$4monthsAgo(): void
$4monthsFromNow
$4monthsFromNow(): void
$4secondsAgo
$4secondsAgo(): void
$4weeksAgo
$4weeksAgo(): void
$4weeksFromNow
$4weeksFromNow(): void
$5daysAgo
$5daysAgo(): void
$5daysFromNow
$5daysFromNow(): void
$5minutesAgo
$5minutesAgo(): void
$5minutesFromNow
$5minutesFromNow(): void
$5monthsAgo
$5monthsAgo(): void
$5monthsFromNow
$5monthsFromNow(): void
$5secondsAgo
$5secondsAgo(): void
$5secondsFromNow
$5secondsFromNow(): void
$6hoursAgo
$6hoursAgo(): void
$6hoursFromNow
$6hoursFromNow(): void
$6monthsAgo
$6monthsAgo(): void
$6monthsFromNow
$6monthsFromNow(): void
$6secondsAgo
$6secondsAgo(): void
$7daysAgo
$7daysAgo(): void
$7daysFromNow
$7daysFromNow(): void
$7secondsAgo
$7secondsAgo(): void
$8hoursAgo
$8hoursAgo(): void
$8hoursFromNow
$8hoursFromNow(): 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