npm-lodash

Description
Comprehensive JavaScript utility library with 300+ methods for arrays, objects, strings, functions, and more.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-lodash@4.5.0

utility-methods.md docs/

1
# Utility Methods
2
3
General-purpose utilities including flow control, constant generation, identity functions, and various helper functions for common programming tasks.
4
5
## Capabilities
6
7
### Core Utility Functions
8
9
#### Identity & No-Operation
10
Basic utility functions for functional programming patterns.
11
12
```javascript { .api }
13
/**
14
* Returns the first argument it receives
15
* @param value - Any value
16
* @returns Returns value
17
*/
18
function identity(value);
19
20
/**
21
* No-operation function that returns undefined regardless of the arguments it receives
22
* @returns Returns undefined
23
*/
24
function noop();
25
26
/**
27
* Creates a function that returns value
28
* @param value - The value to return from the new function
29
* @returns Returns the new constant function
30
*/
31
function constant(value);
32
```
33
34
### Function Creation
35
36
#### Property Access
37
Create functions for property access patterns.
38
39
```javascript { .api }
40
/**
41
* Creates a function that returns the value at path of a given object
42
* @param path - The path of the property to get
43
* @returns Returns the new accessor function
44
*/
45
function property(path);
46
47
/**
48
* The opposite of property; creates a function that returns the value at a given path of object
49
* @param object - The object to query
50
* @returns Returns the new accessor function
51
*/
52
function propertyOf(object);
53
```
54
55
#### Matching Functions
56
Create functions for pattern matching.
57
58
```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 false
61
* @param source - The object of property values to match
62
* @returns Returns the new spec function
63
*/
64
function matches(source);
65
66
/**
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 false
68
* @param path - The path of the property to get
69
* @param srcValue - The value to match
70
* @returns Returns the new spec function
71
*/
72
function matchesProperty(path, srcValue);
73
```
74
75
#### Method Invocation
76
Create functions for method invocation patterns.
77
78
```javascript { .api }
79
/**
80
* Creates a function that invokes the method at path of a given object
81
* @param path - The path of the method to invoke
82
* @param args - The arguments to invoke the method with
83
* @returns Returns the new invoker function
84
*/
85
function method(path, ...args);
86
87
/**
88
* The opposite of method; creates a function that invokes the method at a given path of object
89
* @param object - The object to query
90
* @param args - The arguments to invoke the method with
91
* @returns Returns the new invoker function
92
*/
93
function methodOf(object, ...args);
94
```
95
96
### Function Composition
97
98
#### Flow Control
99
Create function pipelines and composition.
100
101
```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 previous
104
* @param funcs - The functions to invoke
105
* @returns Returns the new composite function
106
*/
107
function flow(...funcs);
108
109
/**
110
* Like flow except that it creates a function that invokes the given functions from right to left
111
* @param funcs - The functions to invoke
112
* @returns Returns the new composite function
113
*/
114
function flowRight(...funcs);
115
```
116
117
#### Predicate Composition
118
Create composite predicate functions.
119
120
```javascript { .api }
121
/**
122
* Creates a function that invokes iteratees with the arguments it receives and returns their results
123
* @param iteratees - The iteratees to invoke
124
* @returns Returns the new function
125
*/
126
function over(...iteratees);
127
128
/**
129
* Creates a function that checks if all predicates return truthy when invoked with the arguments it receives
130
* @param predicates - The predicates to check
131
* @returns Returns the new function
132
*/
133
function overEvery(...predicates);
134
135
/**
136
* Creates a function that checks if any of the predicates return truthy when invoked with the arguments it receives
137
* @param predicates - The predicates to check
138
* @returns Returns the new function
139
*/
140
function overSome(...predicates);
141
```
142
143
### Iteratee Creation
144
145
#### Iteratee Function
146
Create iteratee functions from various inputs.
147
148
```javascript { .api }
149
/**
150
* Creates a function that invokes func with the arguments of the created function
151
* @param func - The value to convert to a callback
152
* @returns Returns the callback
153
*/
154
function iteratee(func);
155
```
156
157
### Conditional Execution
158
159
#### Conditional Function
160
Create conditional execution patterns.
161
162
```javascript { .api }
163
/**
164
* Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy
165
* @param pairs - The predicate-function pairs
166
* @returns Returns the new composite function
167
*/
168
function cond(pairs);
169
170
/**
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 false
172
* @param source - The object of property predicates to conform to
173
* @returns Returns the new spec function
174
*/
175
function conforms(source);
176
```
177
178
### Argument Utilities
179
180
#### Argument Access
181
Create functions for accessing specific arguments.
182
183
```javascript { .api }
184
/**
185
* Creates a function that gets the argument at index n
186
* @param n - The index of the argument to return
187
* @returns Returns the new pass-thru function
188
*/
189
function nthArg(n = 0);
190
```
191
192
### Repetition & Generation
193
194
#### Times Function
195
Execute functions multiple times.
196
197
```javascript { .api }
198
/**
199
* Invokes the iteratee n times, returning an array of the results of each invocation
200
* @param n - The number of times to invoke iteratee
201
* @param iteratee - The function invoked per iteration
202
* @returns Returns the array of results
203
*/
204
function times(n, iteratee);
205
```
206
207
#### Unique ID Generation
208
Generate unique identifiers.
209
210
```javascript { .api }
211
/**
212
* Generates a unique ID
213
* @param prefix - The value to prefix the ID with
214
* @returns Returns the unique ID
215
*/
216
function uniqueId(prefix = '');
217
```
218
219
### Range Generation
220
221
#### Number Ranges
222
Generate ranges of numbers.
223
224
```javascript { .api }
225
/**
226
* Creates an array of numbers progressing from start up to, but not including, end
227
* @param start - The start of the range
228
* @param end - The end of the range
229
* @param step - The value to increment or decrement by
230
* @returns Returns the range of numbers
231
*/
232
function range(start = 0, end, step = 1);
233
234
/**
235
* Like range except that it populates the array in descending order
236
* @param start - The start of the range
237
* @param end - The end of the range
238
* @param step - The value to increment or decrement by
239
* @returns Returns the range of numbers
240
*/
241
function rangeRight(start = 0, end, step = 1);
242
```
243
244
### Default Values
245
246
#### Default Value Utility
247
Provide default values for undefined/null values.
248
249
```javascript { .api }
250
/**
251
* Checks value to determine whether a default value should be returned in its place
252
* @param value - The value to check
253
* @param defaultValue - The default value
254
* @returns Returns the resolved value
255
*/
256
function defaultTo(value, defaultValue);
257
```
258
259
### Path Utilities
260
261
#### Path Conversion
262
Convert values to property paths.
263
264
```javascript { .api }
265
/**
266
* Converts value to a property path array
267
* @param value - The value to convert
268
* @returns Returns the new property path array
269
*/
270
function toPath(value);
271
```
272
273
### Stub Functions
274
275
#### Stub Generators
276
Create functions that return consistent values.
277
278
```javascript { .api }
279
/**
280
* Stub method that returns a new empty array
281
* @returns Returns the new empty array
282
*/
283
function stubArray();
284
285
/**
286
* Stub method that returns false
287
* @returns Returns false
288
*/
289
function stubFalse();
290
291
/**
292
* Stub method that returns a new empty object
293
* @returns Returns the new empty object
294
*/
295
function stubObject();
296
297
/**
298
* Stub method that returns an empty string
299
* @returns Returns the empty string
300
*/
301
function stubString();
302
303
/**
304
* Stub method that returns true
305
* @returns Returns true
306
*/
307
function stubTrue();
308
```
309
310
### Error Handling
311
312
#### Attempt Function
313
Safe function execution with error handling.
314
315
```javascript { .api }
316
/**
317
* Attempts to invoke func, returning either the result or the caught error object
318
* @param func - The function to attempt
319
* @param args - The arguments to invoke func with
320
* @returns Returns the func result or error object
321
*/
322
function attempt(func, ...args);
323
```
324
325
### Library Management
326
327
#### Mixin & No Conflict
328
Extend lodash and manage global namespace.
329
330
```javascript { .api }
331
/**
332
* Adds all own enumerable string keyed function properties of a source object to the destination object
333
* @param object - The destination object
334
* @param source - The object of functions to add
335
* @param options - The options object
336
* @returns Returns object
337
*/
338
function mixin(object, source, options);
339
340
/**
341
* Reverts the _ variable to its previous value and returns a reference to the lodash function
342
* @returns Returns the lodash function
343
*/
344
function noConflict();
345
```
346
347
### Context Creation
348
349
#### Run in Context
350
Create lodash instances with custom context.
351
352
```javascript { .api }
353
/**
354
* Create a pristine lodash function using the context object
355
* @param context - The context object
356
* @returns Returns a new lodash function
357
*/
358
function runInContext(context = root);
359
```
360
361
### Chaining & Flow Control
362
363
#### chain
364
Creates a lodash wrapper instance that wraps value with explicit method chain sequences enabled.
365
366
```javascript { .api }
367
/**
368
* Creates a lodash wrapper instance that wraps value with explicit method chain sequences enabled
369
* @param value - The value to wrap
370
* @returns Returns the new lodash wrapper instance
371
*/
372
function chain(value);
373
```
374
375
#### tap
376
Invokes interceptor and returns value.
377
378
```javascript { .api }
379
/**
380
* Invokes interceptor and returns value
381
* @param value - The value to provide to interceptor
382
* @param interceptor - The function to invoke
383
* @returns Returns value
384
*/
385
function tap(value, interceptor);
386
```
387
388
#### thru
389
Invokes interceptor and returns the result.
390
391
```javascript { .api }
392
/**
393
* Invokes interceptor and returns the result
394
* @param value - The value to provide to interceptor
395
* @param interceptor - The function to invoke
396
* @returns Returns the result of interceptor
397
*/
398
function thru(value, interceptor);
399
```
400
401
### Time Utilities
402
403
#### now
404
Gets the timestamp of the number of milliseconds that have elapsed since the Unix epoch.
405
406
```javascript { .api }
407
/**
408
* Gets the timestamp of the number of milliseconds that have elapsed since the Unix epoch
409
* @returns Returns the timestamp
410
*/
411
function now();
412
```
413
414
## Usage Examples
415
416
```javascript
417
import {
418
identity, noop, constant, property, matches,
419
flow, times, uniqueId, range, defaultTo,
420
attempt, cond, over, stubArray
421
} from "lodash";
422
423
// Basic utility functions
424
console.log(identity(42)); // 42
425
console.log(identity('hello')); // 'hello'
426
console.log(noop()); // undefined
427
428
const alwaysTrue = constant(true);
429
console.log(alwaysTrue()); // true
430
console.log(alwaysTrue(1, 2, 3)); // true
431
432
// Property access functions
433
const getName = property('name');
434
const getAge = property(['profile', 'age']);
435
436
const users = [
437
{ name: 'John', profile: { age: 30 } },
438
{ name: 'Jane', profile: { age: 25 } }
439
];
440
441
console.log(users.map(getName)); // ['John', 'Jane']
442
console.log(users.map(getAge)); // [30, 25]
443
444
// Pattern matching
445
const isAdmin = matches({ role: 'admin', active: true });
446
const hasAdminRole = matchesProperty('role', 'admin');
447
448
const accounts = [
449
{ name: 'John', role: 'admin', active: true },
450
{ name: 'Jane', role: 'user', active: true },
451
{ name: 'Bob', role: 'admin', active: false }
452
];
453
454
console.log(accounts.filter(isAdmin)); // [{ name: 'John', ... }]
455
console.log(accounts.filter(hasAdminRole)); // [John, Bob]
456
457
// Function composition
458
const addOne = x => x + 1;
459
const double = x => x * 2;
460
const square = x => x * x;
461
462
const transform = flow(addOne, double, square);
463
console.log(transform(3)); // ((3 + 1) * 2)² = 64
464
465
const transformReverse = flowRight(square, double, addOne);
466
console.log(transformReverse(3)); // (3 + 1)² * 2 = 32
467
468
// Repetition and generation
469
const zeros = times(5, constant(0));
470
console.log(zeros); // [0, 0, 0, 0, 0]
471
472
const squares = times(5, i => i * i);
473
console.log(squares); // [0, 1, 4, 9, 16]
474
475
const ids = times(3, () => uniqueId('user_'));
476
console.log(ids); // ['user_1', 'user_2', 'user_3']
477
478
// Range generation
479
console.log(range(4)); // [0, 1, 2, 3]
480
console.log(range(1, 5)); // [1, 2, 3, 4]
481
console.log(range(0, 20, 5)); // [0, 5, 10, 15]
482
console.log(rangeRight(4)); // [3, 2, 1, 0]
483
484
// Default values
485
const config = {
486
host: undefined,
487
port: null,
488
timeout: 5000
489
};
490
491
const safeConfig = {
492
host: defaultTo(config.host, 'localhost'),
493
port: defaultTo(config.port, 3000),
494
timeout: defaultTo(config.timeout, 10000)
495
};
496
497
console.log(safeConfig); // { host: 'localhost', port: 3000, timeout: 5000 }
498
499
// Safe function execution
500
const riskyOperation = (x) => {
501
if (x < 0) throw new Error('Negative number');
502
return Math.sqrt(x);
503
};
504
505
console.log(attempt(riskyOperation, 16)); // 4
506
console.log(attempt(riskyOperation, -4)); // Error object
507
508
// Conditional execution
509
const classify = cond([
510
[x => x < 0, constant('negative')],
511
[x => x === 0, constant('zero')],
512
[x => x > 0, constant('positive')]
513
]);
514
515
console.log(classify(-5)); // 'negative'
516
console.log(classify(0)); // 'zero'
517
console.log(classify(10)); // 'positive'
518
519
// Multiple function application
520
const getStats = over([
521
arr => arr.length,
522
arr => Math.max(...arr),
523
arr => Math.min(...arr),
524
arr => arr.reduce((a, b) => a + b, 0) / arr.length
525
]);
526
527
const numbers = [1, 2, 3, 4, 5];
528
const [count, max, min, avg] = getStats(numbers);
529
console.log({ count, max, min, avg }); // { count: 5, max: 5, min: 1, avg: 3 }
530
531
// Practical utility examples
532
533
// Create a validation pipeline
534
const validators = [
535
value => typeof value === 'string',
536
value => value.length > 0,
537
value => value.length <= 50
538
];
539
540
const isValidString = overEvery(validators);
541
console.log(isValidString('hello')); // true
542
console.log(isValidString('')); // false
543
console.log(isValidString(123)); // false
544
545
// Create a data processing pipeline
546
const processData = flow(
547
data => data.filter(item => item.active),
548
data => data.map(item => ({ ...item, processed: true })),
549
data => data.sort((a, b) => a.priority - b.priority)
550
);
551
552
const rawData = [
553
{ id: 1, active: true, priority: 3 },
554
{ id: 2, active: false, priority: 1 },
555
{ id: 3, active: true, priority: 2 }
556
];
557
558
console.log(processData(rawData));
559
560
// Create configuration factory
561
function createConfig(overrides = {}) {
562
const defaults = {
563
timeout: 5000,
564
retries: 3,
565
host: 'localhost',
566
port: 3000
567
};
568
569
return Object.keys(defaults).reduce((config, key) => {
570
config[key] = defaultTo(overrides[key], defaults[key]);
571
return config;
572
}, {});
573
}
574
575
console.log(createConfig({ port: 8080 }));
576
// { timeout: 5000, retries: 3, host: 'localhost', port: 8080 }
577
578
// Create test data generators
579
const generateUser = (index) => ({
580
id: uniqueId('user_'),
581
name: `User ${index + 1}`,
582
email: `user${index + 1}@example.com`,
583
active: Math.random() > 0.5
584
});
585
586
const testUsers = times(5, generateUser);
587
console.log(testUsers);
588
589
// Create reusable predicates
590
const isEven = x => x % 2 === 0;
591
const isPositive = x => x > 0;
592
const isSmall = x => x < 10;
593
594
const isEvenPositive = overEvery([isEven, isPositive]);
595
const isEvenOrSmall = overSome([isEven, isSmall]);
596
597
console.log(isEvenPositive(4)); // true
598
console.log(isEvenPositive(-4)); // false
599
console.log(isEvenOrSmall(3)); // true (small)
600
console.log(isEvenOrSmall(12)); // true (even)
601
602
// Create initialization system
603
const initTasks = [
604
() => console.log('Loading config...'),
605
() => console.log('Connecting to database...'),
606
() => console.log('Starting server...')
607
];
608
609
const runInitialization = () => {
610
initTasks.forEach((task, index) => {
611
setTimeout(task, index * 1000);
612
});
613
};
614
615
// Create factory functions
616
const createGetters = (fields) => {
617
return fields.reduce((getters, field) => {
618
getters[`get${field.charAt(0).toUpperCase() + field.slice(1)}`] = property(field);
619
return getters;
620
}, {});
621
};
622
623
const userGetters = createGetters(['name', 'email', 'age']);
624
const user = { name: 'John', email: 'john@example.com', age: 30 };
625
626
console.log(userGetters.getName(user)); // 'John'
627
console.log(userGetters.getEmail(user)); // 'john@example.com'
628
```