package-utils
Helper utility modules for collections, arrays, objects and more.
Inspired by _
. 😄
Install
Install with npm
$ npm install @jonkemp/package-utils
Usage
forEach
Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed. Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list). Returns the list for chaining.
forEach([1, 2, 3], alert);
forEach({one: 1, two: 2, three: 3}, alert);
map
Produces a new array of values by mapping each value in list through a transformation function (iteratee). The iteratee is passed three arguments: the value, then the index (or key) of the iteration, and finally a reference to the entire list.
map([1, 2, 3], num => num * 3);
map({one: 1, two: 2, three: 3}, (num, key) => num * 3);
map([[1, 2], [3, 4]], first);
flatten
Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.
flatten([1, [2], [3, [[4]]]]);
flatten([1, [2], [3, [[4]]]], true);
allKeys
Retrieve all the names of object's own and inherited properties.
function Stooge(name) {
this.name = name;
}
Stooge.prototype.silly = true;
allKeys(new Stooge("Moe"));
property
Returns a function that will return the specified property of any passed-in object. path may be specified as a simple key, or as an array of object keys or array indexes, for deep property fetching.
const stooge = {name: 'moe'};
'moe' === property('name')(stooge);
const stooges = {moe: {fears: {worst: 'Spiders'}}, curly: {fears: {worst: 'Moe'}}};
const curlysWorstFear = property(['curly', 'fears', 'worst']);
curlysWorstFear(stooges);
matcher
Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs.
const ready = matcher({selected: true, visible: true});
const readyToGoList = filter(list, ready);
isFunction
Returns true if object is a Function.
isFunction(alert);
isNumber
Returns true if object is a Number (including NaN).
isNumber(8.4 * 5);
isUndefined
Returns true if value is undefined.
isUndefined(window.missingVariable);
identity
Returns the same value that is used as the argument. In math: f(x) = x
This function looks useless, but is used throughout Underscore as a default iteratee.
const stooge = { name: 'moe' };
stooge === identity(stooge);
constant
Creates a function that returns the same value that is used as the argument of constant.
const stooge = { name: 'moe' };
stooge === constant(stooge)();
Like us a lot? Help others know why you like us! Review this package on pkgreview.dev | ➡ | |
---|
License
MIT