My personal collection of utility functions.
- juliutils
- yes
- no
- withinNDaysOf
- printDate
- printCSVDate
- omitEmpty
- uniq
- difference
- partition
- mode
- groupBy
- indexBy
- arrAverage
- flatten
- compact
- flattenCompact
- range
- randomString
- pickKeys
- createTree
- transformObj
- clone
- arrToKeys
- isNumber
- truncate
- basicPlural
- valuesAsKeys
- escapeCSV
- escapeRegExp
- escapeHTML
- takeNRandom
- promiseSeries
- delayPromise
- sleep
- deepEqual
- without
- shorten
- roundN
- closest
- chainSort
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 mm/dd/YYYY 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.
obj
Object Object to omit values from.
Returns Object Object with null, undefined, or empty string values omitted.
Gets unique values from array.
Returns Array Array with unique values.
Meta
- since: 1.0.5 - The filter parameter was added.
Gets difference between two arrays.
Returns Array Array with values removed.
Partitions array based on conditions.
Returns Array Partitioned array.
Returns mode from array of numbers.
numbers
Array Array of numbers.
Returns (Number | undefined) Mode of numbers, or undefined if array is empty.
Groups an array by value from key.
Returns Object Object of groups.
Indexes an array by value from key.
Returns Object Indexed object.
Averages an array of values.
numbers
values
Array Array of values.
Returns Number Average of all values in array.
Flattens an array.
Returns Array Flattened array.
Removes all falsy values from an array.
arr
Array Array to compact.
Returns Array Compacted array.
Flattens and compacts array.
arr
Array Array to flatten and compact.deep
Boolean? Whether the array should be flattened recursively.
Returns Array Flattened and compacted array.
Creates a range of numbers from start to stop, not including the stop value.
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'.ender
any? Any value to use as the end value.
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. (optional, default{}
)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
Creates an object from an array of keys.
keys
Array Array of keys.value
any? Value to assign to each key.
arrToKeys(['a', 'b'], 0);
// { a: 0, b: 0 }
Returns Object 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.
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 N number of values taken from array at random.
Executes a series of Promises in sequence.
funcs
Array 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> Promise that resolves with an array containing results from each resolved Promise in 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
any Value A.b
any Value B.
Returns Boolean Whether A is equal to B.
Removes elements from an object or array by value.
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) Object or array without the given values.
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 Array of anything. If comparing non-numbers, a key should be given.num
Number Number to be closest to.key
(String | function) 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 11m
closest([
{
name: 'New York',
population: 8.6
},
{
name: 'Tokyo',
population: 13.8
},
{
name: 'Mumbai',
population: 12.4
}
], 11, 'population');
// { name: 'Mumbai', population: 12.4 }
Returns any Closest value in array.
Sorts an array in a chain.
chainSort([1, 5, 9, 4, 2], [
(a, b) => {
return a - b;
}
]);
// [1, 2, 4, 5, 9]
Returns Array Sorted array.