0
# Function Utilities
1
2
Higher-order functions for controlling execution, binding context, and creating specialized functions. These utilities enable advanced functional programming patterns and performance optimizations.
3
4
## Capabilities
5
6
### Debounce
7
8
Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.
9
10
```javascript { .api }
11
/**
12
* Creates a debounced function that delays invoking `func` until after `wait`
13
* milliseconds have elapsed since the last time the debounced function was
14
* invoked. The debounced function comes with a `cancel` method to cancel
15
* delayed invocations and a `flush` method to immediately invoke them.
16
*
17
* @param {Function} func The function to debounce.
18
* @param {number} [wait=0] The number of milliseconds to delay.
19
* @param {Object} [options={}] The options object.
20
* @param {boolean} [options.leading=false] Specify invoking on the leading edge of the timeout.
21
* @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's invoked.
22
* @param {boolean} [options.trailing=true] Specify invoking on the trailing edge of the timeout.
23
* @returns {Function} Returns the new debounced function.
24
*/
25
function debounce(func, wait, options);
26
```
27
28
**Usage Examples:**
29
30
```javascript
31
var debounce = require('lodash.debounce');
32
33
// Avoid costly calculations while the window size is in flux
34
var lazyLayout = debounce(calculateLayout, 150);
35
window.addEventListener('resize', lazyLayout);
36
37
// Invoke on leading edge
38
var leadingDebounce = debounce(updateStatus, 200, { leading: true });
39
40
// Cancel debounced function
41
var debounced = debounce(save, 1000);
42
// Later cancel the call
43
debounced.cancel();
44
45
// Immediately invoke
46
debounced.flush();
47
```
48
49
### Throttle
50
51
Creates a throttled function that only invokes func at most once per every wait milliseconds.
52
53
```javascript { .api }
54
/**
55
* Creates a throttled function that only invokes `func` at most once per
56
* every `wait` milliseconds. The throttled function comes with a `cancel`
57
* method to cancel delayed invocations and a `flush` method to immediately
58
* invoke them.
59
*
60
* @param {Function} func The function to throttle.
61
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
62
* @param {Object} [options={}] The options object.
63
* @param {boolean} [options.leading=true] Specify invoking on the leading edge of the timeout.
64
* @param {boolean} [options.trailing=true] Specify invoking on the trailing edge of the timeout.
65
* @returns {Function} Returns the new throttled function.
66
*/
67
function throttle(func, wait, options);
68
```
69
70
**Usage Examples:**
71
72
```javascript
73
var throttle = require('lodash.throttle');
74
75
// Avoid excessive scroll handler calls
76
var throttledScroll = throttle(updateScrollPosition, 100);
77
window.addEventListener('scroll', throttledScroll);
78
79
// Throttle with options
80
var throttled = throttle(fetchData, 300, { leading: false });
81
```
82
83
### Once
84
85
Creates a function that is restricted to invoking func once.
86
87
```javascript { .api }
88
/**
89
* Creates a function that is restricted to invoking `func` once. Repeat calls
90
* to the function return the value of the first call. The `func` is invoked
91
* with the `this` binding and arguments of the created function.
92
*
93
* @param {Function} func The function to restrict.
94
* @returns {Function} Returns the new restricted function.
95
*/
96
function once(func);
97
```
98
99
**Usage Examples:**
100
101
```javascript
102
var once = require('lodash.once');
103
104
var initialize = once(function() {
105
console.log('App initialized');
106
// expensive initialization logic
107
});
108
109
initialize(); // 'App initialized'
110
initialize(); // no output, function not called again
111
```
112
113
### Bind
114
115
Creates a function that invokes func with the this binding of thisArg and prepends any additional arguments.
116
117
```javascript { .api }
118
/**
119
* Creates a function that invokes `func` with the `this` binding of `thisArg`
120
* and prepends any additional `bind` arguments to those provided to the bound function.
121
*
122
* @param {Function} func The function to bind.
123
* @param {*} thisArg The `this` binding of `func`.
124
* @param {...*} [partials] The arguments to be partially applied.
125
* @returns {Function} Returns the new bound function.
126
*/
127
function bind(func, thisArg, ...partials);
128
```
129
130
**Usage Examples:**
131
132
```javascript
133
var bind = require('lodash.bind');
134
135
function greet(greeting, punctuation) {
136
return greeting + ' ' + this.user + punctuation;
137
}
138
139
var object = { user: 'alice' };
140
141
// Bind with context
142
var boundGreet = bind(greet, object);
143
boundGreet('hello', '!');
144
// => 'hello alice!'
145
146
// Bind with context and partial arguments
147
var boundSayHello = bind(greet, object, 'hello');
148
boundSayHello('!');
149
// => 'hello alice!'
150
```
151
152
### Curry
153
154
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 arguments.
155
156
```javascript { .api }
157
/**
158
* Creates a function that accepts arguments of `func` and either invokes
159
* `func` returning its result, if at least `arity` number of arguments have
160
* been provided, or returns a function that accepts the remaining `func`
161
* arguments, and so on.
162
*
163
* @param {Function} func The function to curry.
164
* @param {number} [arity=func.length] The arity of `func`.
165
* @returns {Function} Returns the new curried function.
166
*/
167
function curry(func, arity);
168
```
169
170
**Usage Examples:**
171
172
```javascript
173
var curry = require('lodash.curry');
174
175
var abc = function(a, b, c) {
176
return [a, b, c];
177
};
178
179
var curried = curry(abc);
180
181
curried(1)(2)(3);
182
// => [1, 2, 3]
183
184
curried(1, 2)(3);
185
// => [1, 2, 3]
186
187
curried(1, 2, 3);
188
// => [1, 2, 3]
189
```
190
191
### Partial
192
193
Creates a function that invokes func with partials prepended to the arguments it receives.
194
195
```javascript { .api }
196
/**
197
* Creates a function that invokes `func` with `partials` prepended to the
198
* arguments it receives. This method is like `_.bind` except it does **not**
199
* alter the `this` binding.
200
*
201
* @param {Function} func The function to partially apply arguments to.
202
* @param {...*} [partials] The arguments to be partially applied.
203
* @returns {Function} Returns the new partially applied function.
204
*/
205
function partial(func, ...partials);
206
```
207
208
**Usage Examples:**
209
210
```javascript
211
var partial = require('lodash.partial');
212
213
function greet(greeting, name) {
214
return greeting + ' ' + name;
215
}
216
217
var sayHelloTo = partial(greet, 'hello');
218
sayHelloTo('alice');
219
// => 'hello alice'
220
221
// Use placeholders
222
var greetFred = partial(greet, _, 'fred');
223
greetFred('hi');
224
// => 'hi fred'
225
```
226
227
### Memoize
228
229
Creates a function that memoizes the result of func.
230
231
```javascript { .api }
232
/**
233
* Creates a function that memoizes the result of `func`. If `resolver` is
234
* provided it determines the cache key for storing the result based on the
235
* arguments provided to the memoized function. By default, the first argument
236
* provided to the memoized function is used as the map cache key.
237
*
238
* @param {Function} func The function to have its output memoized.
239
* @param {Function} [resolver] The function to resolve the cache key.
240
* @returns {Function} Returns the new memoizing function.
241
*/
242
function memoize(func, resolver);
243
```
244
245
**Usage Examples:**
246
247
```javascript
248
var memoize = require('lodash.memoize');
249
250
var fibonacci = memoize(function(n) {
251
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
252
});
253
254
fibonacci(10); // Computed once
255
fibonacci(10); // Retrieved from cache
256
257
// Custom resolver
258
var memoized = memoize(expensiveFunction, function(obj) {
259
return obj.id;
260
});
261
```
262
263
### Delay
264
265
Invokes func after wait milliseconds.
266
267
```javascript { .api }
268
/**
269
* Invokes `func` after `wait` milliseconds. Any additional arguments are
270
* provided to `func` when it's invoked.
271
*
272
* @param {Function} func The function to delay.
273
* @param {number} wait The number of milliseconds to delay invocation.
274
* @param {...*} [args] The arguments to invoke `func` with.
275
* @returns {number} Returns the timer id.
276
*/
277
function delay(func, wait, ...args);
278
```
279
280
**Usage Examples:**
281
282
```javascript
283
var delay = require('lodash.delay');
284
285
delay(function(text) {
286
console.log(text);
287
}, 1000, 'later');
288
// => logs 'later' after one second
289
```
290
291
### Defer
292
293
Defers invoking the func until the current call stack has cleared.
294
295
```javascript { .api }
296
/**
297
* Defers invoking the `func` until the current call stack has cleared. Any
298
* additional arguments are provided to `func` when it's invoked.
299
*
300
* @param {Function} func The function to defer.
301
* @param {...*} [args] The arguments to invoke `func` with.
302
* @returns {number} Returns the timer id.
303
*/
304
function defer(func, ...args);
305
```
306
307
**Usage Examples:**
308
309
```javascript
310
var defer = require('lodash.defer');
311
312
defer(function(text) {
313
console.log(text);
314
}, 'deferred');
315
// logs 'deferred' after the current call stack has cleared
316
```
317
318
## Additional Functions
319
320
The function utilities category also includes: `after`, `ary`, `before`, `bindAll`, `bindKey`, `curryRight`, `flow`, `flowRight`, `negate`, `partialRight`, `rearg`, `wrap`
321
322
**Package Installation:**
323
324
```bash
325
npm install lodash.debounce lodash.throttle lodash.once lodash.bind
326
npm install lodash.curry lodash.partial lodash.memoize lodash.delay
327
npm install lodash.defer
328
```