My personal collection of utility functions.
General purpose utility functions.
Interprets whether a string means yes or not.
str
string Test string.
yes('yes'); // true
yes('yup'); // true
yes('no'); // false
Returns boolean No?
Interprets whether a string means no or not.
str
string Test string.
no('no'); // true
no('nope'); // true
no('yes'); // false
Returns boolean Yes?
Checks whether two dates are within N days of each other.
Returns boolean Whether the two dates are within N days of each other.
Prints a date as a string in YYYY/mm/dd format.
Returns string String of date.
Prints a date for a CSV file in YYYY/mm/dd format.
date
Date Date to print.
Returns string String of date to be inserted into a CSV cell.
Omits keys with values that are empty from object.
Returns Object<string, any> Object with null, undefined, or empty string values omitted.
Gets unique values from array.
arr
Array<T> Array of items.filter
(string | function (T, number, Array<T>): (number | string))? String or function to filter by.
Returns Array Array with unique values.
Meta
- since: 1.0.5 - The filter parameter was added.
Type: Object<(string | number), boolean>
Gets difference between two arrays.
Returns Array<any> Array with values removed.
Partitions array based on conditions.
Returns [Array<T>, Array<T>] Partitioned array.
Averages an array of numbers.
Returns number Average of all numbers in array.
Averages an array of numbers.
Returns number Average of all numbers in array.
Meta
- deprecated: Since version 1.1.4 - Use
average
instead.
Gets the mean of an array of numbers.
Returns number Average of all numbers in array.
Gets the median from an array of numbers.
Returns (number | undefined) Median of numbers, or undefined if array is empty.
Gets mode from array of numbers.
Returns (number | undefined) Mode of numbers, or undefined if array is empty.
Groups an array by value from key.
Returns Object<string, Array<T>> Object of groups.
Indexes an array by value from key.
Returns Object<string, T> Indexed object.
Flattens an array.
Returns Array<any> Flattened array.
Type: Array<(Array<any> | any)>
Flattens an array (shallow).
Returns Array<(Array<any> | any)> Flattened array.
Type: Array<(Array<any> | any)>
Removes all falsy values from an array.
arr
Array<any> Array to compact.
Returns Array<any> Compacted array.
Flattens and compacts array.
Returns Array<(Array<any> | any)> Flattened and compacted array.
Meta
- deprecated: Since version 1.1.4 - Use
flatten
andcompact
separately.
Creates a range of numbers from start to stop, non-inclusive.
range(1, 3); // [1, 2]
Returns Array Array of numbers in range.
Create a random string.
length
Number Length of string. (optional, default10
)
Returns String Random string.
Picks keys from an object.
obj
Object Object to pick values from.keys
...(string | Array<string>) Keys to pick. Keys can also be contained within an array.
Returns Object Object with picked keys.
Creates a tree within an object.
Modifies the original object.
obj
Object Object to build tree on.tree
Array Tree to build on 'obj'.tail
any? Any value to use as the tail.
createTree({}, ['fruit', 'color'], 'red'); // { fruit: { color: 'red' } }
Returns Object The same object passed as 'obj'.
Recursively transforms key/values in object, including array values.
Also can act as a basic deep clone method.
obj
Object Object to transform.transforms
Object Object containing transformation functions.level
number Level of recursion, passed as the 2nd argument to a transform function. (optional, default0
)
transformObj({
apple: 'Green',
orange: 'Orange',
cherry: {
color: 'Red'
}
}, {
keys: (key, level) => {
return level === 0 ? `fruit_${key}` : key;
},
values: (value) => {
return value.toUpperCase();
}
});
// { fruit_apple: 'GREEN', fruit_orange: 'ORANGE', fruit_cherry: { color: 'RED' } }
Returns Object Transformed object.
Recursively clones an object's values.
This works for simple objects containing simple types like strings, number, and dates. Complex objects containing state may have issues.
obj
Object Object.
Returns Object Cloned object.
Meta
- since: 1.0.7 - method clones more than just primitive values
Type: object
Creates an object from an array of keys.
arrToKeys(['a', 'b'], 0);
// { a: 0, b: 0 }
Returns Object<(string | number), any> Object with keys mapped from array.
Checks if a value is a number or not.
value
any Value to test.
Returns boolean Whether the value is a number or not.
Truncates a string with option to add trail at end.
str
string String.length
number Length to trim to.trail
string Trailing characters. (optional, default''
)
Returns string Truncated string.
Chooses a form based on number.
Returns string Form based on value.
Chooses a form based on number.
Returns string Form based on value.
Meta
- deprecated: Since version 1.1.4 - Use
pluralize
instead.
Assigns values of object as keys.
obj
Object Object.
valuesAsKeys({ a: 'apple' });
// { a: 'apple', 'apple': 'a' }
Returns Object Object with values mapped as keys.
Escapes a cell value in CSV.
str
string String.
Returns string Escaped string.
Escapes a string in RegExp.
str
string String.
Returns string Escaped string.
Escapes text to use as strings in HTML format.
text
string Text to escape.
Returns string Escaped text.
Picks a number of items from an array at random.
takeNRandom([1, 2, 3, 4, 5], 3);
// [3, 5, 2]
Returns Array<any> N number of values taken from array at random.
Picks a number of items from an array at random.
Faster when picking a lower amount of numbers from array.
Returns Array<any> N number of values taken from array at random.
Picks a number of items from an array at random.
Faster when picking a larger amount of numbers from array.
Returns Array<any> N number of values taken from array at random.
Executes a series of Promises in a series, where each Promise resolves before the next function is called.
funcs
Array<(function (): Promise<any>)> An array of functions where each function returns a Promise.
const urls = ['/url1', '/url2', '/url3'];
promiseSeries(urls.map(url => () => $.ajax(url)))
.then(response => console.log(response));
Returns Promise<Array<any>> Promise that resolves with an array containing results from each resolved Promise in series.
Concatenates an array to a list.
list
Array<any> List to concatenate.
Returns function (Array<any>): Array<any> Concatenated list.
Concatenates resolves from previous functions with resolves from current function.
func
function (): Promise<any> Function that returns a Promise.
Returns function (Array<any>): Promise<any> Function that returns a Promise.
Reduces an array of functions that return Promises in series.
accum
Promise<any> Accumulator Promise, this will add a value to the accumulator for each function in the series.func
function (): Promise<any> Function that returns a Promise.
Returns Promise<Array<any>> Promise that resolves with the result of the last function in the series.
Delays a promise.
time
number Time in ms to delay.value
any? Value to pass to resolve.
Returns Promise Promise that resolves after the given delay.
Meta
- since: 1.0.1 - The time parameter comes first.
Sleeps for a set amount of time.
time
number? Time in ms to delay.
Returns Promise Promise that resolves after the given delay.
Checks if A is equal to B.
a
T Value A.b
T Value B.
Returns boolean Whether A is equal to B.
Gets a list of property names of an object.
Returns Array<string> Property names of object.
Checks if all values are the same in both objects.
a
Object<string, any> Object A.b
Object<string, any> Object B.props
Array<any> Properties to check.
Returns boolean Whether all values are the same in both objects.
Checks if a value is an object.
value
any Value to check.
Returns boolean Whether the value is an object.
Removes elements from an object or array by value.
item
(Object | Array<any>) Item to process.value
(any | Array<any>) Value or array of values to remove from item.
without({ name: 'cat', color: 'orange' }, ['orange']); // { name: 'cat' }
without(['cat', 'orange'], ['orange']); // ['cat']
// or using just a string
without(['cat', 'orange'], 'orange'); // ['cat']
Returns (Object | Array<any>) Object or array without the given values.
Checks if an element does not match the value.
element
any Element to check.
Returns boolean Whether the element does not match the value.
Checks if an item does not have a key.
key
string Key to check.
Returns boolean Whether the item does not have the key.
Takes values to remove from 'item' and adds them to a new object.
Returns Object New object with values added.
Shortens a sentence-like string without cutting off the final word.
str
string String to shorten.maxLength
number Max length of string.seperator
(string | RegExp) Word seperator. If a RegExp is given, words will be seperated by a space. (optional, default' '
)
shorten('that cat is fat', 8); // 'that cat'
// custom seperator
shorten('123x456x789', 8, 'x'); // '123x456'
Returns string Shortened string.
Rounds number to N decimal places.
roundN(4.344, 1); // 4.3
Returns number Rounded number.
Gets the closest value to a given number in the array.
arr
Array<T> Array of anything. If comparing non-numbers, a key should be given.num
number Number to be closest to.key
(string | function (T, number): number)? Key or method to extract value from each item.
// gets the closest value in array to 6
closest([1, 5, 9], 6); // 5
// gets the city with the closest population to 11e5
const cities = [
{
name: 'New York',
population: 86e5
},
{
name: 'Tokyo',
population: 138e5
},
{
name: 'Mumbai',
population: 124e5
}
];
closest(cities, 11e5, 'population'); // { name: 'Mumbai', population: 12.4 }
Returns (T | undefined) Closest value in array.
Type: T
Type: number
Sorts an array in a chain.
chainSort([1, 5, 9, 4, 2], [
(a, b) => {
return a - b;
}
]);
// [1, 2, 4, 5, 9]
Returns Array<T> Sorted array.