0
# Function Functions
1
2
Function composition, decoration, and control flow utilities including debouncing, throttling, currying, and memoization.
3
4
## Capabilities
5
6
### Function Timing Control
7
8
Functions for controlling when and how often functions execute.
9
10
```javascript { .api }
11
/**
12
* Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked
13
* @param {Function} func - The function to debounce
14
* @param {number} wait - The number of milliseconds to delay
15
* @param {Object} options - The options object
16
* @param {boolean} options.leading - Specify invoking on the leading edge of the timeout
17
* @param {number} options.maxWait - The maximum time func is allowed to be delayed before it's invoked
18
* @param {boolean} options.trailing - Specify invoking on the trailing edge of the timeout
19
* @returns {Function} Returns the new debounced function
20
*/
21
function debounce(func, wait, options);
22
23
/**
24
* Creates a throttled function that only invokes func at most once per every wait milliseconds
25
* @param {Function} func - The function to throttle
26
* @param {number} wait - The number of milliseconds to throttle invocations to
27
* @param {Object} options - The options object
28
* @param {boolean} options.leading - Specify invoking on the leading edge of the timeout
29
* @param {boolean} options.trailing - Specify invoking on the trailing edge of the timeout
30
* @returns {Function} Returns the new throttled function
31
*/
32
function throttle(func, wait, options);
33
34
/**
35
* Defers invoking the func until the current call stack has cleared
36
* @param {Function} func - The function to defer
37
* @param {...*} args - The arguments to invoke func with
38
* @returns {number} Returns the timer id
39
*/
40
function defer(func, ...args);
41
42
/**
43
* Invokes func after wait milliseconds
44
* @param {Function} func - The function to delay
45
* @param {number} wait - The number of milliseconds to delay invocation
46
* @param {...*} args - The arguments to invoke func with
47
* @returns {number} Returns the timer id
48
*/
49
function delay(func, wait, ...args);
50
```
51
52
### Function Invocation Control
53
54
Functions for controlling how many times and when functions are invoked.
55
56
```javascript { .api }
57
/**
58
* Creates a function that invokes func once it's called n or more times
59
* @param {number} n - The number of calls before func is invoked
60
* @param {Function} func - The function to restrict
61
* @returns {Function} Returns the new restricted function
62
*/
63
function after(n, func);
64
65
/**
66
* Creates a function that invokes func, with up to n calls, while it's called less than n times
67
* @param {number} n - The number of calls at which func is no longer invoked
68
* @param {Function} func - The function to restrict
69
* @returns {Function} Returns the new restricted function
70
*/
71
function before(n, func);
72
73
/**
74
* Creates a function that is restricted to invoking func once
75
* @param {Function} func - The function to restrict
76
* @returns {Function} Returns the new restricted function
77
*/
78
function once(func);
79
```
80
81
### Function Argument Manipulation
82
83
Functions for manipulating function arguments and arity.
84
85
```javascript { .api }
86
/**
87
* Creates a function that invokes func with up to n arguments, ignoring any additional arguments
88
* @param {Function} func - The function to cap arguments for
89
* @param {number} n - The arity cap
90
* @returns {Function} Returns the new capped function
91
*/
92
function ary(func, n);
93
94
/**
95
* Creates a function that accepts up to one argument, ignoring any additional arguments
96
* @param {Function} func - The function to cap arguments for
97
* @returns {Function} Returns the new capped function
98
*/
99
function unary(func);
100
101
/**
102
* Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives
103
* @param {Function} func - The function to bind
104
* @param {*} thisArg - The this binding of func
105
* @param {...*} partials - The arguments to be partially applied
106
* @returns {Function} Returns the new bound function
107
*/
108
function bind(func, thisArg, ...partials);
109
110
/**
111
* Creates a function that invokes func with partials prepended to the arguments it receives
112
* @param {Function} func - The function to partially apply arguments to
113
* @param {...*} partials - The arguments to be partially applied
114
* @returns {Function} Returns the new partially applied function
115
*/
116
function partial(func, ...partials);
117
118
/**
119
* Like partial but partials are appended to the arguments it receives
120
* @param {Function} func - The function to partially apply arguments to
121
* @param {...*} partials - The arguments to be partially applied
122
* @returns {Function} Returns the new partially applied function
123
*/
124
function partialRight(func, ...partials);
125
126
/**
127
* Creates a function that invokes func with arguments arranged according to the specified indexes
128
* @param {Function} func - The function to rearrange arguments for
129
* @param {...(number|number[])} indexes - The arranged argument indexes
130
* @returns {Function} Returns the new function
131
*/
132
function rearg(func, ...indexes);
133
134
/**
135
* Creates a function that invokes func with the transform results of the provided functions
136
* @param {Function} func - The function to wrap
137
* @param {...(Function|Function[])} transforms - The argument transforms
138
* @returns {Function} Returns the new function
139
*/
140
function overArgs(func, ...transforms);
141
```
142
143
### Function Currying
144
145
Functions for creating curried versions of functions.
146
147
```javascript { .api }
148
/**
149
* 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
150
* @param {Function} func - The function to curry
151
* @param {number} arity - The arity of func
152
* @returns {Function} Returns the new curried function
153
*/
154
function curry(func, arity);
155
156
/**
157
* Like curry but arguments are applied to func in the manner of _.partialRight instead of _.partial
158
* @param {Function} func - The function to curry
159
* @param {number} arity - The arity of func
160
* @returns {Function} Returns the new curried function
161
*/
162
function curryRight(func, arity);
163
```
164
165
### Function Composition and Flow
166
167
Functions for composing and chaining function calls.
168
169
```javascript { .api }
170
/**
171
* Creates a function that invokes func with arguments flipped
172
* @param {Function} func - The function to flip arguments for
173
* @returns {Function} Returns the new flipped function
174
*/
175
function flip(func);
176
177
/**
178
* Creates a function that negates the result of the predicate func
179
* @param {Function} predicate - The predicate to negate
180
* @returns {Function} Returns the new negated function
181
*/
182
function negate(predicate);
183
184
/**
185
* Creates a function that invokes the given functions with the this binding of the created function and returns their results
186
* @param {...(Function|Function[])} funcs - The functions to invoke
187
* @returns {Function} Returns the new function
188
*/
189
function over(...funcs);
190
191
/**
192
* Creates a function that checks if all of the provided functions return truthy when invoked with the arguments it receives
193
* @param {...(Function|Function[])} predicates - The predicates to check
194
* @returns {Function} Returns the new function
195
*/
196
function overEvery(...predicates);
197
198
/**
199
* Creates a function that checks if any of the provided functions return truthy when invoked with the arguments it receives
200
* @param {...(Function|Function[])} predicates - The predicates to check
201
* @returns {Function} Returns the new function
202
*/
203
function overSome(...predicates);
204
```
205
206
### Function Binding
207
208
Functions for binding functions to objects and methods.
209
210
```javascript { .api }
211
/**
212
* Binds methods of an object to the object itself, overwriting the existing method
213
* @param {Object} object - The object to bind and assign the bound methods to
214
* @param {...(string|string[])} methodNames - The object method names to bind
215
* @returns {Object} Returns object
216
*/
217
function bindAll(object, ...methodNames);
218
219
/**
220
* Creates a function that invokes the method at object[key] with partials prepended to the arguments it receives
221
* @param {Object} object - The object to invoke the method on
222
* @param {string} key - The key of the method
223
* @param {...*} partials - The arguments to be partially applied
224
* @returns {Function} Returns the new bound function
225
*/
226
function bindKey(object, key, ...partials);
227
```
228
229
### Conditional Function Creation
230
231
Functions for creating conditional and rule-based functions.
232
233
```javascript { .api }
234
/**
235
* Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy
236
* @param {Array} pairs - The predicate-function pairs
237
* @returns {Function} Returns the new composite function
238
*/
239
function cond(pairs);
240
241
/**
242
* Creates a function that invokes the method at a given path on source
243
* @param {Array|string} path - The path of the method to invoke
244
* @param {...*} args - The arguments to invoke the method with
245
* @returns {Function} Returns the new invoker function
246
*/
247
function method(path, ...args);
248
249
/**
250
* Creates a function that invokes the method at path of a given object
251
* @param {Object} object - The object to query
252
* @param {...*} args - The arguments to invoke the method with
253
* @returns {Function} Returns the new invoker function
254
*/
255
function methodOf(object, ...args);
256
```
257
258
### Function Flow Control
259
260
Functions for creating function pipelines and composition.
261
262
```javascript { .api }
263
/**
264
* Creates a function that returns the result of invoking the given functions with the this binding, where each successive invocation is supplied the return value of the previous
265
* @param {...(Function|Function[])} funcs - The functions to invoke
266
* @returns {Function} Returns the new composite function
267
*/
268
function flow(...funcs);
269
270
/**
271
* Creates a function that returns the result of invoking the given functions with the this binding, where each successive invocation is supplied the return value of the previous (right-to-left)
272
* @param {...(Function|Function[])} funcs - The functions to invoke
273
* @returns {Function} Returns the new composite function
274
*/
275
function flowRight(...funcs);
276
277
/**
278
* Creates a function that invokes object[src] with the this binding and arguments of the created function
279
* @param {Object} object - The object to query
280
* @param {string} src - The property name of the method to invoke
281
* @returns {Function} Returns the new invoker function
282
*/
283
function conforms(source);
284
```
285
286
### Framework Integration
287
288
Functions for adding methods to the lodash wrapper and extending functionality.
289
290
```javascript { .api }
291
/**
292
* Adds all own enumerable string keyed function properties of a source object to the destination object
293
* @param {Object} object - The destination object
294
* @param {Object} source - The object of functions to add
295
* @param {Object} options - The options object
296
* @param {string} options.chain - Specify whether mixins are chainable
297
* @returns {Function} Returns func
298
*/
299
function mixin(object, source, options);
300
```
301
302
### Function Memoization
303
304
Functions for caching function results.
305
306
```javascript { .api }
307
/**
308
* Creates a function that memoizes the result of func
309
* @param {Function} func - The function to have its output memoized
310
* @param {Function} resolver - The function to resolve the cache key
311
* @returns {Function} Returns the new memoized function
312
*/
313
function memoize(func, resolver);
314
```
315
316
### Function Rest Parameters
317
318
Functions for handling rest parameters and spreading arguments.
319
320
```javascript { .api }
321
/**
322
* Creates a function that invokes func with the this binding of the created function and an array of arguments much like Function#apply
323
* @param {Function} func - The function to spread arguments over
324
* @param {number} start - The start position of the spread
325
* @returns {Function} Returns the new function
326
*/
327
function spread(func, start);
328
329
/**
330
* Creates a function that accepts one or more arguments of func that when invoked returns the result of invoking func with all arguments from start and beyond provided as an array
331
* @param {Function} func - The function to apply a rest parameter to
332
* @param {number} start - The start position of the rest parameter
333
* @returns {Function} Returns the new function
334
*/
335
function rest(func, start);
336
```
337
338
### Function Wrapping
339
340
Functions for wrapping and decorating other functions.
341
342
```javascript { .api }
343
/**
344
* Creates a function that provides value to wrapper as its first argument
345
* @param {*} value - The value to wrap
346
* @param {Function} wrapper - The wrapper function
347
* @returns {Function} Returns the new function
348
*/
349
function wrap(value, wrapper);
350
```
351
352
## Usage Examples
353
354
### Debouncing and Throttling
355
356
```javascript
357
import { debounce, throttle } from "lodash-es";
358
359
// Debounce example - search input
360
const searchAPI = (query) => {
361
console.log("Searching for:", query);
362
// Make API call
363
};
364
365
const debouncedSearch = debounce(searchAPI, 300);
366
367
// Only calls searchAPI 300ms after the last input
368
document.getElementById("search").addEventListener("input", (e) => {
369
debouncedSearch(e.target.value);
370
});
371
372
// Throttle example - scroll handler
373
const handleScroll = () => {
374
console.log("Scroll position:", window.scrollY);
375
// Update UI based on scroll
376
};
377
378
const throttledScroll = throttle(handleScroll, 100);
379
380
// Only calls handleScroll at most once every 100ms
381
window.addEventListener("scroll", throttledScroll);
382
383
// Advanced debounce with options
384
const saveData = debounce(
385
(data) => {
386
console.log("Saving:", data);
387
// Save to server
388
},
389
1000,
390
{
391
leading: false, // Don't call on leading edge
392
trailing: true, // Call on trailing edge (default)
393
maxWait: 5000 // Force call after 5 seconds max
394
}
395
);
396
```
397
398
### Function Invocation Control
399
400
```javascript
401
import { once, after, before } from "lodash-es";
402
403
// Execute only once
404
const initialize = once(() => {
405
console.log("App initialized");
406
// Expensive initialization logic
407
});
408
409
initialize(); // "App initialized"
410
initialize(); // Won't execute again
411
initialize(); // Won't execute again
412
413
// Execute after n calls
414
const readyAfterThree = after(3, () => {
415
console.log("Ready after 3 calls");
416
});
417
418
readyAfterThree(); // Nothing happens
419
readyAfterThree(); // Nothing happens
420
readyAfterThree(); // "Ready after 3 calls"
421
422
// Execute while less than n calls
423
const limitedFunction = before(3, (x) => {
424
console.log("Called with:", x);
425
return x * 2;
426
});
427
428
limitedFunction(1); // "Called with: 1", returns 2
429
limitedFunction(2); // "Called with: 2", returns 4
430
limitedFunction(3); // Nothing happens, returns undefined
431
```
432
433
### Currying and Partial Application
434
435
```javascript
436
import { curry, partial, partialRight } from "lodash-es";
437
438
// Currying
439
const add = (a, b, c) => a + b + c;
440
const curriedAdd = curry(add);
441
442
// Use curried function
443
const add5 = curriedAdd(5);
444
const add5And3 = add5(3);
445
const result = add5And3(2); // 10
446
447
// Or chain immediately
448
const result2 = curriedAdd(1)(2)(3); // 6
449
450
// Partial application
451
const greet = (greeting, name, punctuation) =>
452
`${greeting} ${name}${punctuation}`;
453
454
const sayHello = partial(greet, "Hello");
455
const hello = sayHello("Alice", "!"); // "Hello Alice!"
456
457
const addExclamation = partialRight(greet, "!");
458
const excited = addExclamation("Hi", "Bob"); // "Hi Bob!"
459
460
// Placeholder support
461
const greetAlice = partial(greet, partial.placeholder, "Alice");
462
const hiAlice = greetAlice("Hi", "!"); // "Hi Alice!"
463
```
464
465
### Function Composition
466
467
```javascript
468
import { flow, flowRight, over, overEvery, overSome } from "lodash-es";
469
470
// Function flow (left to right)
471
const addThenMultiply = flow(
472
(x) => x + 1,
473
(x) => x * 2,
474
(x) => x - 3
475
);
476
477
const result = addThenMultiply(5); // ((5 + 1) * 2) - 3 = 9
478
479
// Function composition (right to left)
480
const multiplyThenAdd = flowRight(
481
(x) => x - 3,
482
(x) => x * 2,
483
(x) => x + 1
484
);
485
486
// Over - call multiple functions with same arguments
487
const logAndReturn = over(
488
console.log,
489
(x) => x * 2
490
);
491
492
const doubled = logAndReturn(5); // Logs 5, returns [undefined, 10]
493
494
// OverEvery - all predicates must be true
495
const isPositiveEven = overEvery(
496
(x) => x > 0,
497
(x) => x % 2 === 0
498
);
499
500
console.log(isPositiveEven(4)); // true
501
console.log(isPositiveEven(-4)); // false
502
503
// OverSome - at least one predicate must be true
504
const isStringOrNumber = overSome(
505
(x) => typeof x === "string",
506
(x) => typeof x === "number"
507
);
508
509
console.log(isStringOrNumber("hello")); // true
510
console.log(isStringOrNumber(42)); // true
511
console.log(isStringOrNumber({})); // false
512
```
513
514
### Memoization
515
516
```javascript
517
import { memoize } from "lodash-es";
518
519
// Expensive recursive function
520
const fibonacci = memoize((n) => {
521
if (n < 2) return n;
522
return fibonacci(n - 1) + fibonacci(n - 2);
523
});
524
525
console.log(fibonacci(40)); // Fast after memoization
526
527
// Custom resolver
528
const getUserData = memoize(
529
(user) => {
530
console.log("Fetching data for:", user.id);
531
// Expensive API call
532
return { data: `User ${user.id} data` };
533
},
534
(user) => user.id // Cache key resolver
535
);
536
537
const user1 = { id: 1, name: "Alice" };
538
const user2 = { id: 1, name: "Alice Updated" };
539
540
getUserData(user1); // "Fetching data for: 1"
541
getUserData(user2); // Uses cache (same ID)
542
543
// Clear cache
544
fibonacci.cache.clear();
545
```
546
547
### Advanced Function Manipulation
548
549
```javascript
550
import { ary, flip, negate, wrap, spread, rest } from "lodash-es";
551
552
// Limit function arity
553
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);
554
const binarySum = ary(sum, 2);
555
556
console.log(sum(1, 2, 3, 4)); // 10
557
console.log(binarySum(1, 2, 3, 4)); // 3 (only uses first 2 args)
558
559
// Flip arguments
560
const divide = (a, b) => a / b;
561
const flippedDivide = flip(divide);
562
563
console.log(divide(10, 2)); // 5
564
console.log(flippedDivide(10, 2)); // 0.2 (2 / 10)
565
566
// Negate predicate
567
const isEven = (x) => x % 2 === 0;
568
const isOdd = negate(isEven);
569
570
console.log(isEven(4)); // true
571
console.log(isOdd(4)); // false
572
573
// Wrap functions
574
const greetWrapper = wrap("Hello", (greeting, name) =>
575
`${greeting} ${name}!`
576
);
577
578
console.log(greetWrapper("World")); // "Hello World!"
579
580
// Spread arguments
581
const arraySum = (arr) => arr.reduce((a, b) => a + b, 0);
582
const spreadSum = spread(arraySum);
583
584
console.log(spreadSum(1, 2, 3, 4)); // 10
585
586
// Rest parameters
587
const logAll = rest((prefix, ...args) => {
588
console.log(prefix, args);
589
});
590
591
logAll("Numbers:", 1, 2, 3); // "Numbers: [1, 2, 3]"
592
```