- Spec files
npm-lodash
Describes: pkg:npm/lodash@4.5.x
- Description
- Comprehensive JavaScript utility library with 300+ methods for arrays, objects, strings, functions, and more.
- Author
- tessl
- Last updated
utility-methods.md docs/
1# Utility Methods23General-purpose utilities including flow control, constant generation, identity functions, and various helper functions for common programming tasks.45## Capabilities67### Core Utility Functions89#### Identity & No-Operation10Basic utility functions for functional programming patterns.1112```javascript { .api }13/**14* Returns the first argument it receives15* @param value - Any value16* @returns Returns value17*/18function identity(value);1920/**21* No-operation function that returns undefined regardless of the arguments it receives22* @returns Returns undefined23*/24function noop();2526/**27* Creates a function that returns value28* @param value - The value to return from the new function29* @returns Returns the new constant function30*/31function constant(value);32```3334### Function Creation3536#### Property Access37Create functions for property access patterns.3839```javascript { .api }40/**41* Creates a function that returns the value at path of a given object42* @param path - The path of the property to get43* @returns Returns the new accessor function44*/45function property(path);4647/**48* The opposite of property; creates a function that returns the value at a given path of object49* @param object - The object to query50* @returns Returns the new accessor function51*/52function propertyOf(object);53```5455#### Matching Functions56Create functions for pattern matching.5758```javascript { .api }59/**60* Creates a function that performs a partial deep comparison between a given object and source, returning true if the given object has equivalent property values, else false61* @param source - The object of property values to match62* @returns Returns the new spec function63*/64function matches(source);6566/**67* Creates a function that performs a partial deep comparison between the value at path of a given object to srcValue, returning true if the object value is equivalent, else false68* @param path - The path of the property to get69* @param srcValue - The value to match70* @returns Returns the new spec function71*/72function matchesProperty(path, srcValue);73```7475#### Method Invocation76Create functions for method invocation patterns.7778```javascript { .api }79/**80* Creates a function that invokes the method at path of a given object81* @param path - The path of the method to invoke82* @param args - The arguments to invoke the method with83* @returns Returns the new invoker function84*/85function method(path, ...args);8687/**88* The opposite of method; creates a function that invokes the method at a given path of object89* @param object - The object to query90* @param args - The arguments to invoke the method with91* @returns Returns the new invoker function92*/93function methodOf(object, ...args);94```9596### Function Composition9798#### Flow Control99Create function pipelines and composition.100101```javascript { .api }102/**103* Creates a function that returns the result of invoking the given functions with the this binding of the created function, where each successive invocation is supplied the return value of the previous104* @param funcs - The functions to invoke105* @returns Returns the new composite function106*/107function flow(...funcs);108109/**110* Like flow except that it creates a function that invokes the given functions from right to left111* @param funcs - The functions to invoke112* @returns Returns the new composite function113*/114function flowRight(...funcs);115```116117#### Predicate Composition118Create composite predicate functions.119120```javascript { .api }121/**122* Creates a function that invokes iteratees with the arguments it receives and returns their results123* @param iteratees - The iteratees to invoke124* @returns Returns the new function125*/126function over(...iteratees);127128/**129* Creates a function that checks if all predicates return truthy when invoked with the arguments it receives130* @param predicates - The predicates to check131* @returns Returns the new function132*/133function overEvery(...predicates);134135/**136* Creates a function that checks if any of the predicates return truthy when invoked with the arguments it receives137* @param predicates - The predicates to check138* @returns Returns the new function139*/140function overSome(...predicates);141```142143### Iteratee Creation144145#### Iteratee Function146Create iteratee functions from various inputs.147148```javascript { .api }149/**150* Creates a function that invokes func with the arguments of the created function151* @param func - The value to convert to a callback152* @returns Returns the callback153*/154function iteratee(func);155```156157### Conditional Execution158159#### Conditional Function160Create conditional execution patterns.161162```javascript { .api }163/**164* Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy165* @param pairs - The predicate-function pairs166* @returns Returns the new composite function167*/168function cond(pairs);169170/**171* Creates a function that invokes the predicate properties of source with the corresponding property values of a given object, returning true if all predicates return truthy, else false172* @param source - The object of property predicates to conform to173* @returns Returns the new spec function174*/175function conforms(source);176```177178### Argument Utilities179180#### Argument Access181Create functions for accessing specific arguments.182183```javascript { .api }184/**185* Creates a function that gets the argument at index n186* @param n - The index of the argument to return187* @returns Returns the new pass-thru function188*/189function nthArg(n = 0);190```191192### Repetition & Generation193194#### Times Function195Execute functions multiple times.196197```javascript { .api }198/**199* Invokes the iteratee n times, returning an array of the results of each invocation200* @param n - The number of times to invoke iteratee201* @param iteratee - The function invoked per iteration202* @returns Returns the array of results203*/204function times(n, iteratee);205```206207#### Unique ID Generation208Generate unique identifiers.209210```javascript { .api }211/**212* Generates a unique ID213* @param prefix - The value to prefix the ID with214* @returns Returns the unique ID215*/216function uniqueId(prefix = '');217```218219### Range Generation220221#### Number Ranges222Generate ranges of numbers.223224```javascript { .api }225/**226* Creates an array of numbers progressing from start up to, but not including, end227* @param start - The start of the range228* @param end - The end of the range229* @param step - The value to increment or decrement by230* @returns Returns the range of numbers231*/232function range(start = 0, end, step = 1);233234/**235* Like range except that it populates the array in descending order236* @param start - The start of the range237* @param end - The end of the range238* @param step - The value to increment or decrement by239* @returns Returns the range of numbers240*/241function rangeRight(start = 0, end, step = 1);242```243244### Default Values245246#### Default Value Utility247Provide default values for undefined/null values.248249```javascript { .api }250/**251* Checks value to determine whether a default value should be returned in its place252* @param value - The value to check253* @param defaultValue - The default value254* @returns Returns the resolved value255*/256function defaultTo(value, defaultValue);257```258259### Path Utilities260261#### Path Conversion262Convert values to property paths.263264```javascript { .api }265/**266* Converts value to a property path array267* @param value - The value to convert268* @returns Returns the new property path array269*/270function toPath(value);271```272273### Stub Functions274275#### Stub Generators276Create functions that return consistent values.277278```javascript { .api }279/**280* Stub method that returns a new empty array281* @returns Returns the new empty array282*/283function stubArray();284285/**286* Stub method that returns false287* @returns Returns false288*/289function stubFalse();290291/**292* Stub method that returns a new empty object293* @returns Returns the new empty object294*/295function stubObject();296297/**298* Stub method that returns an empty string299* @returns Returns the empty string300*/301function stubString();302303/**304* Stub method that returns true305* @returns Returns true306*/307function stubTrue();308```309310### Error Handling311312#### Attempt Function313Safe function execution with error handling.314315```javascript { .api }316/**317* Attempts to invoke func, returning either the result or the caught error object318* @param func - The function to attempt319* @param args - The arguments to invoke func with320* @returns Returns the func result or error object321*/322function attempt(func, ...args);323```324325### Library Management326327#### Mixin & No Conflict328Extend lodash and manage global namespace.329330```javascript { .api }331/**332* Adds all own enumerable string keyed function properties of a source object to the destination object333* @param object - The destination object334* @param source - The object of functions to add335* @param options - The options object336* @returns Returns object337*/338function mixin(object, source, options);339340/**341* Reverts the _ variable to its previous value and returns a reference to the lodash function342* @returns Returns the lodash function343*/344function noConflict();345```346347### Context Creation348349#### Run in Context350Create lodash instances with custom context.351352```javascript { .api }353/**354* Create a pristine lodash function using the context object355* @param context - The context object356* @returns Returns a new lodash function357*/358function runInContext(context = root);359```360361### Chaining & Flow Control362363#### chain364Creates a lodash wrapper instance that wraps value with explicit method chain sequences enabled.365366```javascript { .api }367/**368* Creates a lodash wrapper instance that wraps value with explicit method chain sequences enabled369* @param value - The value to wrap370* @returns Returns the new lodash wrapper instance371*/372function chain(value);373```374375#### tap376Invokes interceptor and returns value.377378```javascript { .api }379/**380* Invokes interceptor and returns value381* @param value - The value to provide to interceptor382* @param interceptor - The function to invoke383* @returns Returns value384*/385function tap(value, interceptor);386```387388#### thru389Invokes interceptor and returns the result.390391```javascript { .api }392/**393* Invokes interceptor and returns the result394* @param value - The value to provide to interceptor395* @param interceptor - The function to invoke396* @returns Returns the result of interceptor397*/398function thru(value, interceptor);399```400401### Time Utilities402403#### now404Gets the timestamp of the number of milliseconds that have elapsed since the Unix epoch.405406```javascript { .api }407/**408* Gets the timestamp of the number of milliseconds that have elapsed since the Unix epoch409* @returns Returns the timestamp410*/411function now();412```413414## Usage Examples415416```javascript417import {418identity, noop, constant, property, matches,419flow, times, uniqueId, range, defaultTo,420attempt, cond, over, stubArray421} from "lodash";422423// Basic utility functions424console.log(identity(42)); // 42425console.log(identity('hello')); // 'hello'426console.log(noop()); // undefined427428const alwaysTrue = constant(true);429console.log(alwaysTrue()); // true430console.log(alwaysTrue(1, 2, 3)); // true431432// Property access functions433const getName = property('name');434const getAge = property(['profile', 'age']);435436const users = [437{ name: 'John', profile: { age: 30 } },438{ name: 'Jane', profile: { age: 25 } }439];440441console.log(users.map(getName)); // ['John', 'Jane']442console.log(users.map(getAge)); // [30, 25]443444// Pattern matching445const isAdmin = matches({ role: 'admin', active: true });446const hasAdminRole = matchesProperty('role', 'admin');447448const accounts = [449{ name: 'John', role: 'admin', active: true },450{ name: 'Jane', role: 'user', active: true },451{ name: 'Bob', role: 'admin', active: false }452];453454console.log(accounts.filter(isAdmin)); // [{ name: 'John', ... }]455console.log(accounts.filter(hasAdminRole)); // [John, Bob]456457// Function composition458const addOne = x => x + 1;459const double = x => x * 2;460const square = x => x * x;461462const transform = flow(addOne, double, square);463console.log(transform(3)); // ((3 + 1) * 2)² = 64464465const transformReverse = flowRight(square, double, addOne);466console.log(transformReverse(3)); // (3 + 1)² * 2 = 32467468// Repetition and generation469const zeros = times(5, constant(0));470console.log(zeros); // [0, 0, 0, 0, 0]471472const squares = times(5, i => i * i);473console.log(squares); // [0, 1, 4, 9, 16]474475const ids = times(3, () => uniqueId('user_'));476console.log(ids); // ['user_1', 'user_2', 'user_3']477478// Range generation479console.log(range(4)); // [0, 1, 2, 3]480console.log(range(1, 5)); // [1, 2, 3, 4]481console.log(range(0, 20, 5)); // [0, 5, 10, 15]482console.log(rangeRight(4)); // [3, 2, 1, 0]483484// Default values485const config = {486host: undefined,487port: null,488timeout: 5000489};490491const safeConfig = {492host: defaultTo(config.host, 'localhost'),493port: defaultTo(config.port, 3000),494timeout: defaultTo(config.timeout, 10000)495};496497console.log(safeConfig); // { host: 'localhost', port: 3000, timeout: 5000 }498499// Safe function execution500const riskyOperation = (x) => {501if (x < 0) throw new Error('Negative number');502return Math.sqrt(x);503};504505console.log(attempt(riskyOperation, 16)); // 4506console.log(attempt(riskyOperation, -4)); // Error object507508// Conditional execution509const classify = cond([510[x => x < 0, constant('negative')],511[x => x === 0, constant('zero')],512[x => x > 0, constant('positive')]513]);514515console.log(classify(-5)); // 'negative'516console.log(classify(0)); // 'zero'517console.log(classify(10)); // 'positive'518519// Multiple function application520const getStats = over([521arr => arr.length,522arr => Math.max(...arr),523arr => Math.min(...arr),524arr => arr.reduce((a, b) => a + b, 0) / arr.length525]);526527const numbers = [1, 2, 3, 4, 5];528const [count, max, min, avg] = getStats(numbers);529console.log({ count, max, min, avg }); // { count: 5, max: 5, min: 1, avg: 3 }530531// Practical utility examples532533// Create a validation pipeline534const validators = [535value => typeof value === 'string',536value => value.length > 0,537value => value.length <= 50538];539540const isValidString = overEvery(validators);541console.log(isValidString('hello')); // true542console.log(isValidString('')); // false543console.log(isValidString(123)); // false544545// Create a data processing pipeline546const processData = flow(547data => data.filter(item => item.active),548data => data.map(item => ({ ...item, processed: true })),549data => data.sort((a, b) => a.priority - b.priority)550);551552const rawData = [553{ id: 1, active: true, priority: 3 },554{ id: 2, active: false, priority: 1 },555{ id: 3, active: true, priority: 2 }556];557558console.log(processData(rawData));559560// Create configuration factory561function createConfig(overrides = {}) {562const defaults = {563timeout: 5000,564retries: 3,565host: 'localhost',566port: 3000567};568569return Object.keys(defaults).reduce((config, key) => {570config[key] = defaultTo(overrides[key], defaults[key]);571return config;572}, {});573}574575console.log(createConfig({ port: 8080 }));576// { timeout: 5000, retries: 3, host: 'localhost', port: 8080 }577578// Create test data generators579const generateUser = (index) => ({580id: uniqueId('user_'),581name: `User ${index + 1}`,582email: `user${index + 1}@example.com`,583active: Math.random() > 0.5584});585586const testUsers = times(5, generateUser);587console.log(testUsers);588589// Create reusable predicates590const isEven = x => x % 2 === 0;591const isPositive = x => x > 0;592const isSmall = x => x < 10;593594const isEvenPositive = overEvery([isEven, isPositive]);595const isEvenOrSmall = overSome([isEven, isSmall]);596597console.log(isEvenPositive(4)); // true598console.log(isEvenPositive(-4)); // false599console.log(isEvenOrSmall(3)); // true (small)600console.log(isEvenOrSmall(12)); // true (even)601602// Create initialization system603const initTasks = [604() => console.log('Loading config...'),605() => console.log('Connecting to database...'),606() => console.log('Starting server...')607];608609const runInitialization = () => {610initTasks.forEach((task, index) => {611setTimeout(task, index * 1000);612});613};614615// Create factory functions616const createGetters = (fields) => {617return fields.reduce((getters, field) => {618getters[`get${field.charAt(0).toUpperCase() + field.slice(1)}`] = property(field);619return getters;620}, {});621};622623const userGetters = createGetters(['name', 'email', 'age']);624const user = { name: 'John', email: 'john@example.com', age: 30 };625626console.log(userGetters.getName(user)); // 'John'627console.log(userGetters.getEmail(user)); // 'john@example.com'628```