- Spec files
npm-lodash
Describes: pkg:npm/lodash@4.6.x
- Description
- A modern JavaScript utility library delivering modularity, performance & extras
- Author
- tessl
- Last updated
util.md docs/
1# General Utilities23Miscellaneous utilities including iteration, constants, method chaining, and utility functions that don't fit into other categories.45## Capabilities67### Iteration Utilities89Create arrays and iterate specific numbers of times.1011```javascript { .api }12/**13* Invokes the iteratee `n` times, returning an array of the results of14* each invocation.15*16* @param {number} n The number of times to invoke `iteratee`17* @param {Function} [iteratee] The function invoked per iteration18* @returns {Array} Returns the array of results19*/20function times(n: number, iteratee?: Function): Array;2122/**23* Creates an array of numbers (positive and/or negative) progressing from24* `start` up to, but not including, `end`. A step of `-1` is used if a negative25* `start` is specified without an `end` or `step`.26*27* @param {number} [start=0] The start of the range28* @param {number} end The end of the range29* @param {number} [step=1] The value to increment or decrement by30* @returns {Array} Returns the range of numbers31*/32function range(start?: number, end?: number, step?: number): Array;3334/**35* This method is like `range` except that it populates values in36* descending order.37*38* @param {number} [start=0] The start of the range39* @param {number} end The end of the range40* @param {number} [step=1] The value to increment or decrement by41* @returns {Array} Returns the range of numbers42*/43function rangeRight(start?: number, end?: number, step?: number): Array;44```4546**Usage Examples:**4748```javascript49import { times, range, rangeRight } from "lodash";5051times(3, String); // ['0', '1', '2']52times(4, () => 'a'); // ['a', 'a', 'a', 'a']53times(3); // [0, 1, 2]5455range(4); // [0, 1, 2, 3]56range(-4); // [0, -1, -2, -3]57range(1, 5); // [1, 2, 3, 4]58range(0, 20, 5); // [0, 5, 10, 15]59range(0, -4, -1); // [0, -1, -2, -3]6061rangeRight(4); // [3, 2, 1, 0]62rangeRight(-4); // [-3, -2, -1, 0]63rangeRight(1, 5); // [4, 3, 2, 1]64rangeRight(0, 20, 5); // [15, 10, 5, 0]65```6667### Identity and Constants6869Basic utility functions for common operations.7071```javascript { .api }72/**73* This method returns the first argument it receives.74*75* @param {*} value Any value76* @returns {*} Returns `value`77*/78function identity(value: any): any;7980/**81* Creates a function that returns `value`.82*83* @param {*} value The value to return from the new function84* @returns {Function} Returns the new constant function85*/86function constant(value: any): Function;8788/**89* This method returns `undefined`.90*91* @returns {undefined} Returns `undefined`92*/93function noop(): undefined;94```9596**Usage Examples:**9798```javascript99import { identity, constant, noop } from "lodash";100101identity(1); // 1102identity({ a: 1 }); // { a: 1 }103104const object = { 'a': 1 };105const getObject = constant(object);106getObject() === object; // true107108noop(); // undefined109[1, 2, 3].forEach(noop); // does nothing110```111112### Function Creation113114Create functions that return specific values or perform specific tasks.115116```javascript { .api }117/**118* Creates a function that invokes `iteratees` with the arguments it receives119* and returns their results.120*121* @param {...(Function|Function[])} [iteratees] The iteratees to invoke122* @returns {Function} Returns the new function123*/124function over(...iteratees: (Function|Function[])[]): Function;125126/**127* Creates a function that checks if **all** of the `predicates` return128* truthy when invoked with the arguments it receives.129*130* @param {...(Function|Function[])} [predicates] The predicates to check131* @returns {Function} Returns the new function132*/133function overEvery(...predicates: (Function|Function[])[]): Function;134135/**136* Creates a function that checks if **any** of the `predicates` return137* truthy when invoked with the arguments it receives.138*139* @param {...(Function|Function[])} [predicates] The predicates to check140* @returns {Function} Returns the new function141*/142function overSome(...predicates: (Function|Function[])[]): Function;143```144145**Usage Examples:**146147```javascript148import { over, overEvery, overSome } from "lodash";149150const func = over([Math.max, Math.min]);151func(1, 2, 3, 4); // [4, 1]152153const func2 = overEvery([Boolean, isFinite]);154func2('1'); // true155func2(null); // false156func2(NaN); // false157158const func3 = overSome([Boolean, isFinite]);159func3('1'); // true160func3(null); // false161func3(NaN); // true (isFinite returns false, but Boolean returns false which is falsy, so isFinite's false is converted to true)162```163164### Property Accessors165166Create functions for accessing object properties.167168```javascript { .api }169/**170* Creates a function that returns the value at `path` of a given object.171*172* @param {Array|string} path The path of the property to get173* @returns {Function} Returns the new accessor function174*/175function property(path: Array|string): Function;176177/**178* The opposite of `property`; this method creates a function that returns179* the value at a given path of `object`.180*181* @param {Object} object The object to query182* @returns {Function} Returns the new accessor function183*/184function propertyOf(object: Object): Function;185```186187**Usage Examples:**188189```javascript190import { property, propertyOf } from "lodash";191192const objects = [193{ 'a': { 'b': 2 } },194{ 'a': { 'b': 1 } }195];196197map(objects, property('a.b')); // [2, 1]198map(objects, property(['a', 'b'])); // [2, 1]199200const array = [0, 1, 2];201const object = { 'a': array, 'b': array, 'c': array };202203map(['a[2]', 'c[0]'], propertyOf(object)); // [2, 0]204```205206### Matching Functions207208Create functions for matching values and properties.209210```javascript { .api }211/**212* Creates a function that performs a partial deep comparison between a given213* object and `source`, returning `true` if the given object has equivalent214* property values, else `false`.215*216* @param {Object} source The object of property values to match217* @returns {Function} Returns the new spec function218*/219function matches(source: Object): Function;220221/**222* Creates a function that performs a partial deep comparison between the223* value at `path` of a given object to `srcValue`, returning `true` if the224* object value is equivalent, else `false`.225*226* @param {Array|string} path The path of the property to get227* @param {*} srcValue The value to match228* @returns {Function} Returns the new spec function229*/230function matchesProperty(path: Array|string, srcValue: any): Function;231```232233**Usage Examples:**234235```javascript236import { matches, matchesProperty, filter } from "lodash";237238const objects = [239{ 'a': 1, 'b': 2, 'c': 3 },240{ 'a': 4, 'b': 5, 'c': 6 }241];242243filter(objects, matches({ 'a': 4, 'c': 6 })); // [{ 'a': 4, 'b': 5, 'c': 6 }]244245filter(objects, matchesProperty('a', 4)); // [{ 'a': 4, 'b': 5, 'c': 6 }]246filter(objects, matchesProperty(['a'], 4)); // [{ 'a': 4, 'b': 5, 'c': 6 }]247```248249### Method Creation250251Create functions that invoke methods on objects.252253```javascript { .api }254/**255* Creates a function that invokes the method at `path` of a given object.256* Any additional arguments are provided to the invoked method.257*258* @param {Array|string} path The path of the method to invoke259* @param {...*} [args] The arguments to invoke the method with260* @returns {Function} Returns the new invoker function261*/262function method(path: Array|string, ...args: any[]): Function;263264/**265* The opposite of `method`; this method creates a function that invokes266* the method at a given path of `object`. Any additional arguments are267* provided to the invoked method.268*269* @param {Object} object The object to query270* @param {...*} [args] The arguments to invoke the method with271* @returns {Function} Returns the new invoker function272*/273function methodOf(object: Object, ...args: any[]): Function;274```275276### Argument Functions277278Create functions that work with function arguments.279280```javascript { .api }281/**282* Creates a function that gets the argument at index `n`. If `n` is negative,283* the nth argument from the end is returned.284*285* @param {number} [n=0] The index of the argument to return286* @returns {Function} Returns the new pass-thru function287*/288function nthArg(n?: number): Function;289```290291**Usage Examples:**292293```javascript294import { nthArg } from "lodash";295296const func = nthArg(1);297func('a', 'b', 'c', 'd'); // 'b'298299const func2 = nthArg(-2);300func2('a', 'b', 'c', 'd'); // 'c'301```302303### Unique ID Generation304305Generate unique identifiers.306307```javascript { .api }308/**309* Generates a unique ID. If `prefix` is given, the ID is appended to it.310*311* @param {string} [prefix=''] The value to prefix the ID with312* @returns {string} Returns the unique ID313*/314function uniqueId(prefix?: string): string;315```316317**Usage Examples:**318319```javascript320import { uniqueId } from "lodash";321322uniqueId('contact_'); // 'contact_104'323uniqueId(); // '105'324```325326### Path Conversion327328Convert values to property paths.329330```javascript { .api }331/**332* Converts `value` to a property path array.333*334* @param {*} value The value to convert335* @returns {Array} Returns the new property path array336*/337function toPath(value: any): Array;338```339340**Usage Examples:**341342```javascript343import { toPath } from "lodash";344345toPath('a.b.c'); // ['a', 'b', 'c']346toPath('a[0].b.c'); // ['a', '0', 'b', 'c']347toPath(['a', 'b', 'c']); // ['a', 'b', 'c']348```349350### Library Management351352Manage the lodash library itself.353354```javascript { .api }355/**356* Reverts the `_` variable to its previous value and returns a reference to357* the `lodash` function.358*359* @returns {Function} Returns the `lodash` function360*/361function noConflict(): Function;362363/**364* Adds all own enumerable string keyed function properties of a source365* object to the destination object. If `object` is a function, then methods366* are added to its prototype as well.367*368* @param {Function|Object} [object=lodash] The destination object369* @param {Object} source The object of functions to add370* @param {Object} [options] The options object371* @returns {Function|Object} Returns `object`372*/373function mixin(object?: Function|Object, source?: Object, options?: Object): Function|Object;374375/**376* Creates a pristine `lodash` function using the `context` object.377*378* @param {Object} [context=root] The context object379* @returns {Function} Returns a new `lodash` function380*/381function runInContext(context?: Object): Function;382```383384### Iteratee Creation385386Create iteratee functions for use with collection methods.387388```javascript { .api }389/**390* Creates a function that invokes `func` with the arguments of the created391* function. If `func` is a property name, the created function returns the392* property value for a given element. If `func` is an array or object, the393* created function returns `true` for elements that contain the equivalent394* source properties, otherwise it returns `false`.395*396* @param {*} [func=_.identity] The value to convert to a callback397* @returns {Function} Returns the callback398*/399function iteratee(func?: any): Function;400```401402### Conformance Testing403404Create functions that test if values conform to schemas.405406```javascript { .api }407/**408* Creates a function that iterates over `pairs` and invokes the corresponding409* function of the first predicate to return truthy. The predicate-function410* pairs are invoked with the `this` binding and arguments of the created function.411*412* @param {Array} pairs The predicate-function pairs413* @returns {Function} Returns the new composite function414*/415function cond(pairs: Array): Function;416417/**418* Creates a function that invokes the predicate properties of `source` with419* the corresponding property values of a given object, returning `true` if420* all predicates return truthy, else `false`.421*422* @param {Object} source The object of property predicates to conform to423* @returns {Function} Returns the new spec function424*/425function conforms(source: Object): Function;426```427428### Error Handling429430Safely attempt function execution.431432```javascript { .api }433/**434* Attempts to invoke `func`, returning either the result or the caught error435* object. Any additional arguments are provided to `func` when it's invoked.436*437* @param {Function} func The function to attempt438* @param {...*} [args] The arguments to invoke `func` with439* @returns {*} Returns the `func` result or error object440*/441function attempt(func: Function, ...args: any[]): any;442```443444**Usage Examples:**445446```javascript447import { attempt } from "lodash";448449// Successful execution450attempt(function(x) {451return x / 2;452}, 6); // 3453454// Error handling455attempt(function() {456throw new Error('Something went wrong');457}); // Error: Something went wrong458459// Useful for safely parsing JSON460attempt(JSON.parse, '{"a": 1}'); // { a: 1 }461attempt(JSON.parse, '{invalid json}'); // SyntaxError: Unexpected token...462```463464### Method Chaining465466Core utility for creating method chains.467468```javascript { .api }469/**470* Creates a lodash wrapper instance that wraps `value` with explicit method chain sequences enabled.471*472* @param {*} value The value to wrap473* @returns {Object} Returns the new lodash wrapper instance474*/475function chain(value: any): Object;476```477478### Time Utilities479480Utilities for working with time.481482```javascript { .api }483/**484* Gets the timestamp of the number of milliseconds that have elapsed since485* the Unix epoch (1 January 1970 00:00:00 UTC).486*487* @returns {number} Returns the timestamp488*/489function now(): number;490```