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

function-methods.md docs/

1
# Function Methods
2
3
Function composition, currying, throttling, debouncing, and other functional programming utilities. These methods enable advanced function manipulation and control flow patterns.
4
5
## Capabilities
6
7
### Function Control Flow
8
9
#### debounce
10
Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.
11
12
```javascript { .api }
13
/**
14
* Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked
15
* @param func - The function to debounce
16
* @param wait - The number of milliseconds to delay
17
* @param options - The options object
18
* @returns Returns the new debounced function
19
*/
20
function debounce(func, wait = 0, options);
21
22
// Debounce options interface
23
interface DebounceOptions {
24
leading?: boolean; // Invoke on the leading edge of the timeout
25
maxWait?: number; // Maximum time func is allowed to be delayed before it's invoked
26
trailing?: boolean; // Invoke on the trailing edge of the timeout
27
}
28
```
29
30
#### throttle
31
Creates a throttled function that only invokes func at most once per every wait milliseconds.
32
33
```javascript { .api }
34
/**
35
* Creates a throttled function that only invokes func at most once per every wait milliseconds
36
* @param func - The function to throttle
37
* @param wait - The number of milliseconds to throttle invocations to
38
* @param options - The options object
39
* @returns Returns the new throttled function
40
*/
41
function throttle(func, wait = 0, options);
42
43
// Throttle options interface
44
interface ThrottleOptions {
45
leading?: boolean; // Invoke on the leading edge of the timeout
46
trailing?: boolean; // Invoke on the trailing edge of the timeout
47
}
48
```
49
50
### Function Invocation Control
51
52
#### once
53
Creates a function that is restricted to invoking func once.
54
55
```javascript { .api }
56
/**
57
* Creates a function that is restricted to invoking func once
58
* @param func - The function to restrict
59
* @returns Returns the new restricted function
60
*/
61
function once(func);
62
```
63
64
#### after & before
65
Creates functions that invoke func only after/before being called n times.
66
67
```javascript { .api }
68
/**
69
* Creates a function that invokes func once it's called n or more times
70
* @param n - The number of calls before func is invoked
71
* @param func - The function to restrict
72
* @returns Returns the new restricted function
73
*/
74
function after(n, func);
75
76
/**
77
* Creates a function that invokes func while it's called less than n times
78
* @param n - The number of calls at which func is no longer invoked
79
* @param func - The function to restrict
80
* @returns Returns the new restricted function
81
*/
82
function before(n, func);
83
```
84
85
### Function Scheduling
86
87
#### defer
88
Defers invoking func until the current call stack has cleared.
89
90
```javascript { .api }
91
/**
92
* Defers invoking func until the current call stack has cleared
93
* @param func - The function to defer
94
* @param args - The arguments to invoke func with
95
* @returns Returns the timer id
96
*/
97
function defer(func, ...args);
98
```
99
100
#### delay
101
Invokes func after wait milliseconds.
102
103
```javascript { .api }
104
/**
105
* Invokes func after wait milliseconds
106
* @param func - The function to delay
107
* @param wait - The number of milliseconds to delay invocation
108
* @param args - The arguments to invoke func with
109
* @returns Returns the timer id
110
*/
111
function delay(func, wait, ...args);
112
```
113
114
### Function Binding
115
116
#### bind
117
Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives.
118
119
```javascript { .api }
120
/**
121
* Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives
122
* @param func - The function to bind
123
* @param thisArg - The this binding of func
124
* @param partials - The arguments to be partially applied
125
* @returns Returns the new bound function
126
*/
127
function bind(func, thisArg, ...partials);
128
```
129
130
#### bindKey
131
Creates a function that invokes the method at object[key] with partials prepended to the arguments it receives.
132
133
```javascript { .api }
134
/**
135
* Creates a function that invokes the method at object[key] with partials prepended to the arguments it receives
136
* @param object - The object to invoke the method on
137
* @param key - The key of the method
138
* @param partials - The arguments to be partially applied
139
* @returns Returns the new bound function
140
*/
141
function bindKey(object, key, ...partials);
142
```
143
144
#### bindAll
145
Binds methods of an object to the object itself, overwriting the existing methods.
146
147
```javascript { .api }
148
/**
149
* Binds methods of an object to the object itself, overwriting the existing methods
150
* @param object - The object to bind and assign the bound methods to
151
* @param methodNames - The object method names to bind
152
* @returns Returns object
153
*/
154
function bindAll(object, methodNames);
155
```
156
157
### Partial Application
158
159
#### partial
160
Creates a function that invokes func with partials prepended to the arguments it receives.
161
162
```javascript { .api }
163
/**
164
* Creates a function that invokes func with partials prepended to the arguments it receives
165
* @param func - The function to partially apply arguments to
166
* @param partials - The arguments to be partially applied
167
* @returns Returns the new partially applied function
168
*/
169
function partial(func, ...partials);
170
```
171
172
#### partialRight
173
Like partial except that partials are appended to the arguments it receives.
174
175
```javascript { .api }
176
/**
177
* Like partial except that partials are appended to the arguments it receives
178
* @param func - The function to partially apply arguments to
179
* @param partials - The arguments to be partially applied
180
* @returns Returns the new partially applied function
181
*/
182
function partialRight(func, ...partials);
183
```
184
185
### Currying
186
187
#### curry
188
Creates a function that accepts arguments of func and either invokes func returning its result, if at least arity number of arguments have been provided, or returns a function that accepts the remaining func arguments.
189
190
```javascript { .api }
191
/**
192
* Creates a function that accepts arguments of func and either invokes func returning its result, if at least arity number of arguments have been provided, or returns a function that accepts the remaining func arguments
193
* @param func - The function to curry
194
* @param arity - The arity of func
195
* @returns Returns the new curried function
196
*/
197
function curry(func, arity = func.length);
198
```
199
200
#### curryRight
201
Like curry except that arguments are applied to func in the manner of partialRight instead of partial.
202
203
```javascript { .api }
204
/**
205
* Like curry except that arguments are applied to func in the manner of partialRight instead of partial
206
* @param func - The function to curry
207
* @param arity - The arity of func
208
* @returns Returns the new curried function
209
*/
210
function curryRight(func, arity = func.length);
211
```
212
213
### Function Transformation
214
215
#### flip
216
Creates a function that invokes func with arguments reversed.
217
218
```javascript { .api }
219
/**
220
* Creates a function that invokes func with arguments reversed
221
* @param func - The function to flip arguments for
222
* @returns Returns the new flipped function
223
*/
224
function flip(func);
225
```
226
227
#### negate
228
Creates a function that negates the result of the predicate func.
229
230
```javascript { .api }
231
/**
232
* Creates a function that negates the result of the predicate func
233
* @param predicate - The predicate to negate
234
* @returns Returns the new negated function
235
*/
236
function negate(predicate);
237
```
238
239
### Argument Manipulation
240
241
#### ary
242
Creates a function that invokes func, with up to n arguments, ignoring any additional arguments.
243
244
```javascript { .api }
245
/**
246
* Creates a function that invokes func, with up to n arguments, ignoring any additional arguments
247
* @param func - The function to cap arguments for
248
* @param n - The arity cap
249
* @returns Returns the new capped function
250
*/
251
function ary(func, n = func.length);
252
```
253
254
#### unary
255
Creates a function that accepts up to one argument, ignoring any additional arguments.
256
257
```javascript { .api }
258
/**
259
* Creates a function that accepts up to one argument, ignoring any additional arguments
260
* @param func - The function to cap arguments for
261
* @returns Returns the new capped function
262
*/
263
function unary(func);
264
```
265
266
#### rest
267
Creates a function that invokes func with the this binding of the created function and arguments from start and beyond provided as an array.
268
269
```javascript { .api }
270
/**
271
* Creates a function that invokes func with the this binding of the created function and arguments from start and beyond provided as an array
272
* @param func - The function to apply a rest parameter to
273
* @param start - The start position of the rest parameter
274
* @returns Returns the new function
275
*/
276
function rest(func, start = func.length - 1);
277
```
278
279
#### spread
280
Creates a function that invokes func with the this binding of the created function and an array of arguments much like Function#apply.
281
282
```javascript { .api }
283
/**
284
* Creates a function that invokes func with the this binding of the created function and an array of arguments much like Function#apply
285
* @param func - The function to spread arguments over
286
* @param start - The start position of the spread
287
* @returns Returns the new function
288
*/
289
function spread(func, start = 0);
290
```
291
292
#### rearg
293
Creates a function that invokes func with arguments arranged according to the specified indexes.
294
295
```javascript { .api }
296
/**
297
* Creates a function that invokes func with arguments arranged according to the specified indexes
298
* @param func - The function to arrange arguments for
299
* @param indexes - The arranged argument indexes
300
* @returns Returns the new function
301
*/
302
function rearg(func, ...indexes);
303
```
304
305
### Argument Transformation
306
307
#### overArgs
308
Creates a function that invokes func with its arguments transformed.
309
310
```javascript { .api }
311
/**
312
* Creates a function that invokes func with its arguments transformed
313
* @param func - The function to wrap
314
* @param transforms - The argument transforms
315
* @returns Returns the new function
316
*/
317
function overArgs(func, ...transforms);
318
```
319
320
### Function Caching
321
322
#### memoize
323
Creates a function that memoizes the result of func.
324
325
```javascript { .api }
326
/**
327
* Creates a function that memoizes the result of func
328
* @param func - The function to have its output memoized
329
* @param resolver - The function to resolve the cache key
330
* @returns Returns the new memoized function
331
*/
332
function memoize(func, resolver);
333
334
// Memoized function interface
335
interface MemoizedFunction {
336
(...args: any[]): any;
337
cache: Map<any, any>;
338
}
339
```
340
341
### Function Wrapping
342
343
#### wrap
344
Creates a function that provides value to wrapper as its first argument.
345
346
```javascript { .api }
347
/**
348
* Creates a function that provides value to wrapper as its first argument
349
* @param value - The value to wrap
350
* @param wrapper - The wrapper function
351
* @returns Returns the new function
352
*/
353
function wrap(value, wrapper);
354
```
355
356
## Usage Examples
357
358
```javascript
359
import {
360
debounce, throttle, once, after, curry, partial,
361
memoize, delay, bind, flip, negate
362
} from "lodash";
363
364
// Debouncing - delay execution until after events stop
365
const searchInput = document.getElementById('search');
366
const performSearch = debounce((query) => {
367
console.log('Searching for:', query);
368
// API call here
369
}, 300);
370
371
searchInput.addEventListener('input', (e) => {
372
performSearch(e.target.value);
373
});
374
375
// Throttling - limit execution frequency
376
const onScroll = throttle(() => {
377
console.log('Scroll position:', window.scrollY);
378
}, 100);
379
380
window.addEventListener('scroll', onScroll);
381
382
// Execute once
383
const initialize = once(() => {
384
console.log('App initialized');
385
// Setup code that should only run once
386
});
387
388
initialize(); // 'App initialized'
389
initialize(); // (nothing happens)
390
391
// Execute after n calls
392
const startApp = after(3, () => {
393
console.log('All resources loaded, starting app');
394
});
395
396
// Called when each resource loads
397
startApp(); // (nothing happens)
398
startApp(); // (nothing happens)
399
startApp(); // 'All resources loaded, starting app'
400
401
// Currying
402
const add = (a, b, c) => a + b + c;
403
const curriedAdd = curry(add);
404
405
const add5 = curriedAdd(5);
406
const add5And3 = add5(3);
407
const result = add5And3(2); // 10
408
409
// Or in one go
410
const result2 = curriedAdd(1)(2)(3); // 6
411
412
// Partial application
413
const multiply = (a, b, c) => a * b * c;
414
const double = partial(multiply, 2);
415
const doubleAndTriple = partial(double, 3);
416
417
console.log(doubleAndTriple(4)); // 2 * 3 * 4 = 24
418
419
// Function memoization
420
const expensiveCalculation = memoize((n) => {
421
console.log(`Computing for ${n}`);
422
return n * n * n;
423
});
424
425
expensiveCalculation(5); // 'Computing for 5', returns 125
426
expensiveCalculation(5); // returns 125 (cached, no log)
427
428
// Custom resolver for memoization
429
const fetchUser = memoize(
430
async (id) => {
431
const response = await fetch(`/api/users/${id}`);
432
return response.json();
433
},
434
(id) => `user:${id}` // cache key resolver
435
);
436
437
// Delayed execution
438
const sayHello = (name) => console.log(`Hello, ${name}!`);
439
delay(sayHello, 1000, 'World'); // Logs after 1 second
440
441
// Function binding
442
const obj = {
443
name: 'MyObject',
444
greet(greeting) {
445
return `${greeting}, I'm ${this.name}`;
446
}
447
};
448
449
const boundGreet = bind(obj.greet, obj);
450
const standaloneGreet = boundGreet;
451
console.log(standaloneGreet('Hello')); // 'Hello, I'm MyObject'
452
453
// Argument flipping
454
const divide = (a, b) => a / b;
455
const flippedDivide = flip(divide);
456
457
console.log(divide(10, 2)); // 5
458
console.log(flippedDivide(10, 2)); // 0.2 (2 / 10)
459
460
// Negation
461
const isEven = (n) => n % 2 === 0;
462
const isOdd = negate(isEven);
463
464
console.log(isEven(4)); // true
465
console.log(isOdd(4)); // false
466
467
// Combining techniques
468
const createApiClient = () => {
469
const cache = new Map();
470
471
const request = memoize(
472
throttle(async (url) => {
473
const response = await fetch(url);
474
return response.json();
475
}, 1000),
476
(url) => url
477
);
478
479
return {
480
get: (endpoint) => request(`/api${endpoint}`)
481
};
482
};
483
484
// Advanced currying example
485
const createLogger = curry((level, category, message) => {
486
console.log(`[${level.toUpperCase()}] ${category}: ${message}`);
487
});
488
489
const errorLogger = createLogger('error');
490
const appErrorLogger = errorLogger('app');
491
const dbErrorLogger = errorLogger('database');
492
493
appErrorLogger('User authentication failed');
494
dbErrorLogger('Connection timeout');
495
496
// Function composition with partial application
497
const users = [
498
{ name: 'John', age: 30, active: true },
499
{ name: 'Jane', age: 25, active: false },
500
{ name: 'Bob', age: 35, active: true }
501
];
502
503
const filterActive = partial(filter, _, 'active');
504
const mapNames = partial(map, _, 'name');
505
const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
506
507
const getActiveUserNames = compose(mapNames, filterActive);
508
console.log(getActiveUserNames(users)); // ['John', 'Bob']
509
```