
Security News
Cloudflare Introduces a Faster TypeScript Compiler Written in Rust
Cloudflare introduces tsrs, a Rust port of TypeScript’s compiler promising faster checks and lower memory use, with the TypeScript team’s help.
@fennecstudio/utils
Advanced tools
A TypeScript utility library with common helper functions.
npm install @fennecstudio/utils
import { formatDate, isEmail, chunk } from '@fennecstudio/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
addDateaddDate(date: any, time: any): void
Adds time intervals to a date
Parameters:
date any - - The date to add time to (string or Date object)time any - - Object containing time intervals to add (seconds, minutes, hours, days)Returns: - The new date with added time
Example:
// Add 2 hours to current date
addDate(new Date(), { hours: 2 })
// Add multiple intervals
addDate('2024-01-01', { days: 5, hours: 3, minutes: 30 })
// Add from ISO string
addDate('2024-01-01T12:00:00Z', { seconds: 45 })
areIdsareIds(ids: string[]): void
Checks if all strings in the array are valid IDs (32 characters long)
Parameters:
ids any - - Array of strings to validateReturns: - True if all strings are valid IDs, false otherwise
Example:
areIds(['a'.repeat(32), 'b'.repeat(32)]) // returns true
areIds(['short', 'ids']) // returns false
areIds(['a'.repeat(32), 'invalid']) // returns false
arraysContainSameValuesarraysContainSameValues(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 compareReturns: - True if arrays contain the same values, false otherwise
Example:
arraysContainSameValues([1, 2, 3], [3, 2, 1]) // returns true
arraysContainSameValues([1, 2], [1, 2, 3]) // returns false
arraysContainSameValues([], []) // returns true
arraysContainSameValues(undefined, undefined) // returns true
Remarks: This function performs a shallow comparison using strict equality (===). For deep object comparison, use with primitive values or references.
atobatob(data: any, encoding?: BufferEncoding): void
Decodes a base64 encoded string
Parameters:
data any - - The base64 encoded data to decodeencoding any - - The character encoding to useReturns: - 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.
base64Decodebase64Decode(base64Str: any): void
Decodes a base64 string back to its original value
Parameters:
base64Str any - - The base64 encoded string to decodeReturns: - The decoded value (string or parsed object), or empty string if decoding fails
Example:
base64Decode('aGVsbG8=') // returns 'hello'
base64Decode('eyJmb28iOiJiYXIifQ==') // returns { foo: 'bar' }
base64Encodebase64Encode(input: string | object): void
Encodes a string or object to base64 format
Parameters:
input any - - The string or object to encodeReturns: - Base64 encoded string, or empty string if encoding fails
Example:
base64Encode('hello') // returns 'aGVsbG8='
base64Encode({ foo: 'bar' }) // returns 'eyJmb28iOiJiYXIifQ=='
basenamebasename(uri: string): void
Extracts the filename without extension from a file path
Parameters:
uri any - - The file path or URIReturns: - The filename without extension, or undefined if no filename found
Example:
basename('/path/to/file.txt') // returns 'file'
basename('C:\\Users\\file.doc') // returns 'file'
basename('document.pdf') // returns 'document'
basename('/path/to/folder/') // returns undefined
Remarks: Handles both forward slashes (/) and backslashes () as path separators.
btoabtoa(data: any): void
Encodes data to base64
Parameters:
data any - - The data to encodeReturns: - 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.
byIdDeprecated: 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 objectsid any - - The unique identifier on which to match against the 'id' fieldReturns: - 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' }
camelCasecamelCase(str: string): string
Converts a string to camelCase format
Parameters:
str any - - The string to convert to camelCaseReturns: - 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.
camelCaseKeyscamelCaseKeys(obj: any): any
Recursively converts object keys from snake_case to camelCase
Parameters:
obj any - - The object to convertReturns: - 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
capitalizecapitalize(str: string): void
Capitalizes the first letter of a string
Parameters:
str any - - The string to capitalizeReturns: - The string with the first letter capitalized
Example:
capitalize('hello') // returns 'Hello'
capitalize('world') // returns 'World'
capitalize('123abc') // returns '123abc'
caseInsensitiveComparecaseInsensitiveCompare(str1: string, str2: string): boolean
Compares two strings case-insensitively
Parameters:
str1 any - - First string to comparestr2 any - - Second string to compareReturns: - True if strings are equal ignoring case, false otherwise
Example:
caseInsensitiveCompare('Hello', 'hello') // returns true
caseInsensitiveCompare('ABC', 'abc') // returns true
caseInsensitiveCompare('foo', 'bar') // returns false
caseInsensitiveIncludescaseInsensitiveIncludes(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 inReturns: - True if the string is found in the array (case-insensitive), false otherwise
Example:
caseInsensitiveIncludes('HELLO', ['hello', 'world']) // returns true
caseInsensitiveIncludes('foo', ['bar', 'baz']) // returns false
caseInsensitiveIncludes('Test', ['test', 'TEST', 'TeSt']) // returns true
chunkchunk(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 chunkReturns: - 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
cleanclean(val: any): void
Cleans a string by escaping quotes and replacing angle brackets
Parameters:
val any - - The value to cleanReturns: - 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
cleanObjectcleanObject(obj: Record<string, any>): Record<string, any>
Recursively removes null, undefined, and empty string values from an object
Parameters:
obj any - - The object to cleanReturns: - 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
cloneclone(value: any): void
Creates a shallow copy of a value
Parameters:
value any - - The value to cloneReturns: - A shallow copy of the value
Example:
clone({ a: 1, b: 2 }) // returns { a: 1, b: 2 }
clone([1, 2, 3]) // returns [1, 2, 3]
clone('string') // returns 'string'
clone(42) // returns 42
Remarks: Only performs shallow cloning - nested objects/arrays still reference the same values. For deep cloning, use a dedicated deep clone utility.
concatconcat(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 arrayReturns: - A new array containing all elements from the input arrays
containscontains(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 forReturns: - True if the value is found, false otherwise
createGatewayEventcreateGatewayEvent(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 -createGroupsDeprecated: 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 -createSnsEventcreateSnsEvent(message: any): void
Creates a mock SNS event object for testing
Parameters:
message any - - The message to include in the SNS eventReturns: - A mock SNS event object
deduplicatededuplicate(array: any[]): void
Removes duplicate values from the given array
Parameters:
array any - - The array to deduplicateReturns: - 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
differencedifference(array1: any[], array2: any[]): any[]
Returns the difference between two arrays
Parameters:
array1 any - - The array to compare fromarray2 any - - The array to compare againstReturns: - 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.
ensureArrayensureArray(array: any | any[]): any[]
Ensures that the given value is an array
Parameters:
array any - - The value to ensure is an arrayReturns: - 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
everyevery(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 elementReturns: - True if all elements pass the test, false otherwise
extensionextension(filename: string): void
Parses the file extension from the given filename, including the '.'
Parameters:
filename any -Returns: - The file extension of the given filename
findByfindBy(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 nameReturns: - The first item in the collection that matches the given id
findByIdfindById(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' propertyReturns: - The first item in the collection that matches the given id
formatCurrencyformatCurrency(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:
formatCurrency(1234.56) // returns "$1,234.56"
formatCurrency(1234.56, 'de-DE', 'EUR') // returns "1.234,56 €"
formatDateformatDate(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')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"
formatPercentageformatPercentage(num: number, precision?: number): string
formatPriceformatPrice(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:
formatPrice(1234.56) // returns "$1,234.56"
formatPrice(1234.56, 2) // returns "$1,234.56"
formatPrice(1234.56, 0) // returns "$1,234"
generateCodegenerateCode(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
generateIdgenerateId(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
generateKeygenerateKey(length?: any): void
Generates a random alphanumeric key
Parameters:
length any - - The length of the key (default: 5)Returns: - A random alphanumeric string
generateUuidgenerateUuid(separator?: any): string
Generates a RFC 4122 compliant UUID v4
Parameters:
separator any - - The separator to use between UUID segmentsReturns: - 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
getCreditCardTypegetCreditCardType(cardNumber?: string): void
Determines the credit card type based on the card number
Parameters:
cardNumber any - - The credit card number to analyzeReturns: - The card type (VISA, MASTERCARD, AMEX, DISCOVER, JCB, DINERSCLUB) or undefined
getCurrencySymbolgetCurrencySymbol(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
groupBygroupBy(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 byReturns: - 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 }] }
hasAnyhasAny(items?: any[]): void
Checks if an array has any elements
Parameters:
items any - - The array to checkReturns: - True if the array has elements, false otherwise
hasLengthhasLength(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
hasManyhasMany(items: any[]): void
Checks if an array has more than one element
Parameters:
items any - - The array to checkReturns: - True if the array has 2 or more elements
hasNonehasNone(items?: any[]): void
Checks if an array has no elements
Parameters:
items any - - The array to checkReturns: - True if the array is empty or null/undefined
hasOnehasOne(items?: any[]): void
Checks if an array has exactly one element
Parameters:
items any - - The array to checkReturns: - True if the array has exactly one element
idid(): void
Generates a unique ID using UUID v4
Returns: - A UUID string
idsids(items?: any[]): void
Extracts and deduplicates IDs from an array of objects
Parameters:
items any - - Array of objects with id propertiesReturns: - Array of unique IDs
ignoreCaseignoreCase(value: string): void
Creates a case-insensitive regular expression for exact matching
Parameters:
value any - - The string to create a regex forReturns: - A case-insensitive RegExp object
includesincludes(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 forReturns: - True if the value is found, false otherwise
intersectintersect(arr1: any, arr2: any): void
Returns the intersection of two arrays
Parameters:
arr1 any -arr2 any -isArrayisArray(value: any): void
Checks if a value is an array
Parameters:
value any - - The value to checkReturns: - True if the value is an array
isBooleanisBoolean(value: string): void
Checks if a string represents a boolean value
Parameters:
value any - - The string to checkReturns: - True if the string is 'true' or 'false' (case-insensitive)
isBufferisBuffer(value: any): void
Checks if a value is a Buffer
Parameters:
value any - - The value to checkReturns: - True if the value is a Buffer
isDateisDate(input: any): boolean
Checks if a value is a valid date or date string
Parameters:
input any - - The value to checkReturns: - True if the value is a valid date
isEmailisEmail(email: string): void
Checks if a string is a valid email address
Parameters:
email any - - The string to checkReturns: - True if the string is a valid email format
isEmptyObjectisEmptyObject(obj?: any): void
Checks if an object is empty (has no own properties)
Parameters:
obj any - - The object to checkReturns: - True if the object is empty or falsy
isEqualisEqual(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 compareReturns: - True if the values are equivalent, false otherwise
Example:
var object = { 'user': 'fred' };
var other = { 'user': 'fred' };
isEqual(object, other);
// => true
object === other;
// => false
isErrorisError(value: any): void
Checks if a value is an Error object
Parameters:
value any - - The value to checkReturns: - True if the value is an Error instance
isExpiredisExpired(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 dateReturns: - True if the date has expired
isIdisId(id?: string): boolean
Checks if a string is a valid ID (32 characters long)
Parameters:
id any - - The string to checkReturns: - True if the string is a valid ID
isInTimeisInTime(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 rangeReturns: - True if the date is within the specified time range
isJsonisJson(value: string): void
Checks if a string is valid JSON
Parameters:
value any - - The string to checkReturns: - True if the string is valid JSON
isNullOrUndefinedisNullOrUndefined(value: any): void
Checks if a value is null or undefined
Parameters:
value any - - The value to checkReturns: - True if the value is null or undefined
isNumberisNumber(value: any): void
Checks if a value is a valid number
Parameters:
value any - - The value to checkReturns: - True if the value is a finite number
isObjectisObject(input: any): boolean
Checks if a value is an object (not array, null, or primitive)
Parameters:
input any - - The value to checkReturns: - True if the value is an object
isOlderThanisOlderThan(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 comparisonReturns: - True if the date is older than the comparison time
isStringisString(input: any): boolean
Checks if a value is a string
Parameters:
input any - - The value to checkReturns: - True if the value is a string
joinWithAndjoinWithAnd(array: string[]): void
Joins an array of strings with commas and 'and' for the last item
Parameters:
array any -keykey(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
keyifykeyify(value: string): string
Converts a string to a URL-friendly key format
Parameters:
value any - - The string to convertReturns: - A URL-friendly string with lowercase letters, numbers, and hyphens
maxValuemaxValue(arr: number[]): void
Finds the maximum value in an array of numbers
Parameters:
arr any - - Array of numbersReturns: - The maximum value
mergemerge(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
minValueminValue(arr: number[]): void
Finds the minimum value in an array of numbers
Parameters:
arr any - - Array of numbersReturns: - The minimum value
nownow(): void
Returns the current date and time
Returns: - A new Date object representing the current time
omitomit(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 objectkeys any - - Array of keys or individual key arguments to omitadditionalKeys any - - Additional keys to omit when using string formatReturns: - A new object without the specified keys
Example:
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
orderNumberorderNumber(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
parseEmailparseEmail(inputString: string): void
Parses an email string that may include a display name
Parameters:
inputString any - - Email string in format "Display Name email@domain.com" or "email@domain.com"Returns: - Object with address and optional displayName properties
parseErrorMessageparseErrorMessage(err: any): void
Extracts an error message from various error formats
Parameters:
err any - - The error object, string, or data structureReturns: - The error message string or undefined
parseFileTypeparseFileType(filePath: string): string
Tries to determine a files content type by its extension
Parameters:
filePath any - - file path or filenameparseFullNameparseFullName(fullName: string): { firstName: string; lastName: string }
Parses a full name into first and last name components
Parameters:
fullName any - - The full name string to parseReturns: - Object with firstName and lastName properties
parseGatewayMessageparseGatewayMessage(event?: any): void
Parses an AWS API Gateway event into a structured message
Parameters:
event any - - The API Gateway event objectReturns: - Object with parsed body, headers, and params
parseJSONparseJSON(input: any): void
Safely parses JSON, returning the original input if parsing fails
Parameters:
input any - - The input to parse as JSONReturns: - 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
parseSnsMessageparseSnsMessage(event?: any): void
Parses an AWS SNS message from an event
Parameters:
event any - - The SNS event objectReturns: - The parsed message or empty object if parsing fails
pastpast(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
pickpick(obj: T, keys: string[] | string, additionalKeys?: string[]): Partial<T>
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 formatReturns: - A new object containing only the specified keys
Example:
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.
pickWithoutpickWithout(obj: T, keys: string[]): Partial<T>
Returns a new object with all keys except the specified keys
Parameters:
obj any -keys any -pluralplural(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
prettypretty(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
pushpush(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
randomrandom(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
randomInRangerandomInRange(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
removeremove(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 removeReturns: - A new array with the value removed
removeEmptyObjectsremoveEmptyObjects(collection?: any): void
Removes empty objects from a collection
Parameters:
collection any - - Array of objects to filterReturns: - Array with empty objects removed
removeEmptyPropertiesremoveEmptyProperties(obj: any): void
Removes empty properties (null, undefined, empty string) from an object
Parameters:
obj any - - The object to cleanReturns: - A new object with empty properties removed
roundround(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
somesome(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 elementReturns: - True if at least one element passes the test
sortBysortBy(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
splitsplit(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
splitEmailssplitEmails(emailList: string): string[]
Splits a string of emails separated by commas or whitespace
Parameters:
emailList any - - String containing multiple email addressesReturns: - Array of trimmed email addresses
splitFullNamesplitFullName(fullName: string): { firstName: string; lastName: string }
Splits a full name into first and last name components
Parameters:
fullName any - - The full name string to splitReturns: - Object with firstName and lastName properties
stringifystringify(data: any): void
Safely converts data to a string representation
Parameters:
data any - - The data to stringifyReturns: - String representation of the data
testtest(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
titleCasetitleCase(str: string): string
Converts a string to title case
Parameters:
str any - - The string to convertReturns: - The string in title case format
toBooleantoBoolean(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
toHashtoHash(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 -toPricetoPrice(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 numbertoSnakeCasetoSnakeCase(obj: any): any
Recursively converts object keys from camelCase to snake_case
Parameters:
obj any - - The object to convertReturns: - Object with snake_case keys
uniqueunique(prefix?: any, suffix?: any): void
Creates a unique value based on the current timestamp Used primarily for testing
Parameters:
prefix any -suffix any -waitwait(ms: number): void
Waits for the specified number of milliseconds
Parameters:
ms any - - The number of milliseconds to waitReturns: - A promise that resolves after the specified time
withoutwithout(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 resultReturns: - A new array without the specified values
delaydelay(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
intervalinterval(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
retryretry(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
copyToClipboardcopyToClipboard(text: string): void
Copies text to the clipboard using the Clipboard API.
Parameters:
text any - - The text to copy to clipboardparamsparams(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
formatRateWindowformatRateWindow(date: any): void
Formats a date as a rate window string.
Parameters:
date any - - The date to formatReturns: - Formatted string (e.g., "Jan, 1st 2:00 pm")
getCurrentRateWindowgetCurrentRateWindow(): void
Gets the current rate window (start of the current hour).
Returns: - Date object representing the start of the current hour
getRateWindowgetRateWindow(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 forReturns: - Date object representing the start of that hour
isCurrentRateWindowisCurrentRateWindow(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
$10minutesAgo$10minutesAgo(): void
$10minutesFromNow$10minutesFromNow(): void
$10secondsAgo$10secondsAgo(): void
$12hoursAgo$12hoursAgo(): void
$1dayAgo$1dayAgo(): void
$1hourAgo$1hourAgo(): void
$1hourFromNow$1hourFromNow(): void
$1minuteAgo$1minuteAgo(): void
$1minuteFromNow$1minuteFromNow(): void
$1monthAgo$1monthAgo(): void
$1secondAgo$1secondAgo(): void
$1secondFromNow$1secondFromNow(): void
$1weekAgo$1weekAgo(): void
$1weekFromNow$1weekFromNow(): void
$1yearAgo$1yearAgo(): void
$24HoursAgo$24HoursAgo(): void
$2daysAgo$2daysAgo(): void
$2daysFromNow$2daysFromNow(): void
$2hoursAgo$2hoursAgo(): void
$2minutesAgo$2minutesAgo(): void
$2monthsAgo$2monthsAgo(): void
$2secondsAgo$2secondsAgo(): void
$2weeksAgo$2weeksAgo(): void
$2weeksFromNow$2weeksFromNow(): void
$30daysAgo$30daysAgo(): void
$30minutesAgo$30minutesAgo(): void
$30secondsAgo$30secondsAgo(): void
$3daysFromNow$3daysFromNow(): void
$3hoursAgo$3hoursAgo(): void
$3minutesAgo$3minutesAgo(): void
$3monthsAgo$3monthsAgo(): void
$3monthsFromNow$3monthsFromNow(): void
$3secondsAgo$3secondsAgo(): void
$45secondsAgo$45secondsAgo(): void
$4minutesAgo$4minutesAgo(): void
$4monthsAgo$4monthsAgo(): void
$4secondsAgo$4secondsAgo(): void
$5minutesAgo$5minutesAgo(): void
$5monthsAgo$5monthsAgo(): void
$5secondsAgo$5secondsAgo(): void
$6hoursAgo$6hoursAgo(): void
$6monthsAgo$6monthsAgo(): void
$6monthsFromNow$6monthsFromNow(): void
$daysFromNow$daysFromNow(days: number): void
$lastWeek$lastWeek(): void
$nextMonth$nextMonth(): void
$nextWeek$nextWeek(): void
$nextYear$nextYear(): void
$today$today(): void
$tomorrow$tomorrow(): void
$yesterday$yesterday(): void
last12hourslast12hours(): void
last24hourslast24hours(): void
last30minuteslast30minutes(): void
addToDay | fromDay | getDayOfWeek | getDaysOfWeek | isDayFormat | lastWeek | lastYear | nextDay | nextWeek | today | toDay | tomorrow | yesterday
addToDayaddToDay(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
fromDayfromDay(day: string, timezone?: string): Date
Converts a date string to a Date object.
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
getDayOfWeekgetDayOfWeek(dateString: string): dayOfWeek
Gets the day of the week for a given date string.
Parameters:
dateString string - - The date string to parseReturns: dayOfWeek - The day of the week as a lowercase string
getDaysOfWeekgetDaysOfWeek(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
isDayFormatisDayFormat(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 validateReturns: - True if the string matches YYYY-MM-DD format and is a valid date, false otherwise
lastWeeklastWeek(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
lastYearlastYear(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
nextDaynextDay(yyyymmdd: string): string
Returns the next day for a given date string.
Parameters:
yyyymmdd string - - The date string in YYYY-MM-DD formatReturns: string - The next day in YYYY-MM-DD format
nextWeeknextWeek(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
todaytoday(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
toDaytoDay(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
tomorrowtomorrow(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
yesterdayyesterday(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
FAQs
A TypeScript utility library with common helper functions.
The npm package @fennecstudio/utils receives a total of 0 weekly downloads. As such, @fennecstudio/utils popularity was classified as not popular.
We found that @fennecstudio/utils demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.

Security News
Cloudflare introduces tsrs, a Rust port of TypeScript’s compiler promising faster checks and lower memory use, with the TypeScript team’s help.

Security News
The PHP Foundation says Chainguard broke a security embargo ahead of critical RCE patches, as leaks disrupted the coordinated release.

Security News
PHP releases emergency patches for two critical RCE vulnerabilities as agencies urge organizations to take unpatched sites offline.