Debian Codegraph @

closure-library/closure/goog/functions/functions.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Utilities for creating functions. Loosely inspired by the
17 * java classes: http://goo.gl/GM0Hmu and http://goo.gl/6k7nI8.
18 *
19 * @author [email protected] (Nick Santos)
20 */
21
22
23 goog.provide('goog.functions');
24
25
26 /**
27 * Creates a function that always returns the same value.
28 * @param {T} retValue The value to return.
29 * @return {function():T} The new function.
30 * @template T
31 */
32 goog.functions.constant = function(retValue) {
33 return function() { return retValue; };
34 };
35
36
37 /**
38 * Always returns false.
39 * @type {function(...): boolean}
40 */
41 goog.functions.FALSE = goog.functions.constant(false);
42
43
44 /**
45 * Always returns true.
46 * @type {function(...): boolean}
47 */
48 goog.functions.TRUE = goog.functions.constant(true);
49
50
51 /**
52 * Always returns NULL.
53 * @type {function(...): null}
54 */
55 goog.functions.NULL = goog.functions.constant(null);
56
57
58 /**
59 * A simple function that returns the first argument of whatever is passed
60 * into it.
61 * @param {T=} opt_returnValue The single value that will be returned.
62 * @param {...*} var_args Optional trailing arguments. These are ignored.
63 * @return {T} The first argument passed in, or undefined if nothing was passed.
64 * @template T
65 */
66 goog.functions.identity = function(opt_returnValue, var_args) {
67 return opt_returnValue;
68 };
69
70
71 /**
72 * Creates a function that always throws an error with the given message.
73 * @param {string} message The error message.
74 * @return {!Function} The error-throwing function.
75 */
76 goog.functions.error = function(message) {
77 return function() {
78 throw new Error(message);
79 };
80 };
81
82
83 /**
84 * Creates a function that throws the given object.
85 * @param {*} err An object to be thrown.
86 * @return {!Function} The error-throwing function.
87 */
88 goog.functions.fail = function(err) {
89 return function() { throw err; };
90 };
91
92
93 /**
94 * Given a function, create a function that keeps opt_numArgs arguments and
95 * silently discards all additional arguments.
96 * @param {Function} f The original function.
97 * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.
98 * @return {!Function} A version of f that only keeps the first opt_numArgs
99 * arguments.
100 */
101 goog.functions.lock = function(f, opt_numArgs) {
102 opt_numArgs = opt_numArgs || 0;
103 return function() {
104 var self = /** @type {*} */ (this);
105 return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));
106 };
107 };
108
109
110 /**
111 * Creates a function that returns its nth argument.
112 * @param {number} n The position of the return argument.
113 * @return {!Function} A new function.
114 */
115 goog.functions.nth = function(n) {
116 return function() { return arguments[n]; };
117 };
118
119
120 /**
121 * Like goog.partial(), except that arguments are added after arguments to the
122 * returned function.
123 *
124 * Usage:
125 * function f(arg1, arg2, arg3, arg4) { ... }
126 * var g = goog.functions.partialRight(f, arg3, arg4);
127 * g(arg1, arg2);
128 *
129 * @param {!Function} fn A function to partially apply.
130 * @param {...*} var_args Additional arguments that are partially applied to fn
131 * at the end.
132 * @return {!Function} A partially-applied form of the function goog.partial()
133 * was invoked as a method of.
134 */
135 goog.functions.partialRight = function(fn, var_args) {
136 var rightArgs = Array.prototype.slice.call(arguments, 1);
137 return function() {
138 var self = /** @type {*} */ (this);
139 var newArgs = Array.prototype.slice.call(arguments);
140 newArgs.push.apply(newArgs, rightArgs);
141 return fn.apply(self, newArgs);
142 };
143 };
144
145
146 /**
147 * Given a function, create a new function that swallows its return value
148 * and replaces it with a new one.
149 * @param {Function} f A function.
150 * @param {T} retValue A new return value.
151 * @return {function(...?):T} A new function.
152 * @template T
153 */
154 goog.functions.withReturnValue = function(f, retValue) {
155 return goog.functions.sequence(f, goog.functions.constant(retValue));
156 };
157
158
159 /**
160 * Creates a function that returns whether its argument equals the given value.
161 *
162 * Example:
163 * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));
164 *
165 * @param {*} value The value to compare to.
166 * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)
167 * comparison rather than a strict (===) one. Defaults to false.
168 * @return {function(*):boolean} The new function.
169 */
170 goog.functions.equalTo = function(value, opt_useLooseComparison) {
171 return function(other) {
172 return opt_useLooseComparison ? (value == other) : (value === other);
173 };
174 };
175
176
177 /**
178 * Creates the composition of the functions passed in.
179 * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).
180 * @param {function(...?):T} fn The final function.
181 * @param {...Function} var_args A list of functions.
182 * @return {function(...?):T} The composition of all inputs.
183 * @template T
184 */
185 goog.functions.compose = function(fn, var_args) {
186 var functions = arguments;
187 var length = functions.length;
188 return function() {
189 var self = /** @type {*} */ (this);
190 var result;
191 if (length) {
192 result = functions[length - 1].apply(self, arguments);
193 }
194
195 for (var i = length - 2; i >= 0; i--) {
196 result = functions[i].call(self, result);
197 }
198 return result;
199 };
200 };
201
202
203 /**
204 * Creates a function that calls the functions passed in in sequence, and
205 * returns the value of the last function. For example,
206 * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).
207 * @param {...Function} var_args A list of functions.
208 * @return {!Function} A function that calls all inputs in sequence.
209 */
210 goog.functions.sequence = function(var_args) {
211 var functions = arguments;
212 var length = functions.length;
213 return function() {
214 var self = /** @type {*} */ (this);
215 var result;
216 for (var i = 0; i < length; i++) {
217 result = functions[i].apply(self, arguments);
218 }
219 return result;
220 };
221 };
222
223
224 /**
225 * Creates a function that returns true if each of its components evaluates
226 * to true. The components are evaluated in order, and the evaluation will be
227 * short-circuited as soon as a function returns false.
228 * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).
229 * @param {...Function} var_args A list of functions.
230 * @return {function(...?):boolean} A function that ANDs its component
231 * functions.
232 */
233 goog.functions.and = function(var_args) {
234 var functions = arguments;
235 var length = functions.length;
236 return function() {
237 var self = /** @type {*} */ (this);
238 for (var i = 0; i < length; i++) {
239 if (!functions[i].apply(self, arguments)) {
240 return false;
241 }
242 }
243 return true;
244 };
245 };
246
247
248 /**
249 * Creates a function that returns true if any of its components evaluates
250 * to true. The components are evaluated in order, and the evaluation will be
251 * short-circuited as soon as a function returns true.
252 * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).
253 * @param {...Function} var_args A list of functions.
254 * @return {function(...?):boolean} A function that ORs its component
255 * functions.
256 */
257 goog.functions.or = function(var_args) {
258 var functions = arguments;
259 var length = functions.length;
260 return function() {
261 var self = /** @type {*} */ (this);
262 for (var i = 0; i < length; i++) {
263 if (functions[i].apply(self, arguments)) {
264 return true;
265 }
266 }
267 return false;
268 };
269 };
270
271
272 /**
273 * Creates a function that returns the Boolean opposite of a provided function.
274 * For example, (goog.functions.not(f))(x) is equivalent to !f(x).
275 * @param {!Function} f The original function.
276 * @return {function(...?):boolean} A function that delegates to f and returns
277 * opposite.
278 */
279 goog.functions.not = function(f) {
280 return function() {
281 var self = /** @type {*} */ (this);
282 return !f.apply(self, arguments);
283 };
284 };
285
286
287 /**
288 * Generic factory function to construct an object given the constructor
289 * and the arguments. Intended to be bound to create object factories.
290 *
291 * Example:
292 *
293 * var factory = goog.partial(goog.functions.create, Class);
294 *
295 * @param {function(new:T, ...)} constructor The constructor for the Object.
296 * @param {...*} var_args The arguments to be passed to the constructor.
297 * @return {T} A new instance of the class given in {@code constructor}.
298 * @template T
299 */
300 goog.functions.create = function(constructor, var_args) {
301 /**
302 * @constructor
303 * @final
304 */
305 var temp = function() {};
306 temp.prototype = constructor.prototype;
307
308 // obj will have constructor's prototype in its chain and
309 // 'obj instanceof constructor' will be true.
310 var obj = new temp();
311
312 // obj is initialized by constructor.
313 // arguments is only array-like so lacks shift(), but can be used with
314 // the Array prototype function.
315 constructor.apply(obj, Array.prototype.slice.call(arguments, 1));
316 return obj;
317 };
318
319
320 /**
321 * @define {boolean} Whether the return value cache should be used.
322 * This should only be used to disable caches when testing.
323 */
324 goog.define('goog.functions.CACHE_RETURN_VALUE', true);
325
326
327 /**
328 * Gives a wrapper function that caches the return value of a parameterless
329 * function when first called.
330 *
331 * When called for the first time, the given function is called and its
332 * return value is cached (thus this is only appropriate for idempotent
333 * functions). Subsequent calls will return the cached return value. This
334 * allows the evaluation of expensive functions to be delayed until first used.
335 *
336 * To cache the return values of functions with parameters, see goog.memoize.
337 *
338 * @param {function():T} fn A function to lazily evaluate.
339 * @return {function():T} A wrapped version the function.
340 * @template T
341 */
342 goog.functions.cacheReturnValue = function(fn) {
343 var called = false;
344 var value;
345
346 return function() {
347 if (!goog.functions.CACHE_RETURN_VALUE) {
348 return fn();
349 }
350
351 if (!called) {
352 value = fn();
353 called = true;
354 }
355
356 return value;
357 };
358 };
359
360
361 /**
362 * Wraps a function to allow it to be called, at most, once. All
363 * additional calls are no-ops.
364 *
365 * This is particularly useful for initialization functions
366 * that should be called, at most, once.
367 *
368 * @param {function():*} f Function to call.
369 * @return {function():undefined} Wrapped function.
370 */
371 goog.functions.once = function(f) {
372 // Keep a reference to the function that we null out when we're done with
373 // it -- that way, the function can be GC'd when we're done with it.
374 var inner = f;
375 return function() {
376 if (inner) {
377 var tmp = inner;
378 inner = null;
379 tmp();
380 }
381 };
382 };
383
384
385 /**
386 * Wraps a function to allow it to be called, at most, once per interval
387 * (specified in milliseconds). If the wrapper function is called N times within
388 * that interval, only the Nth call will go through.
389 *
390 * This is particularly useful for batching up repeated actions where the
391 * last action should win. This can be used, for example, for refreshing an
392 * autocomplete pop-up every so often rather than updating with every keystroke,
393 * since the final text typed by the user is the one that should produce the
394 * final autocomplete results. For more stateful debouncing with support for
395 * pausing, resuming, and canceling debounced actions, use {@code
396 * goog.async.Debouncer}.
397 *
398 * @param {function(this:SCOPE, ...?)} f Function to call.
399 * @param {number} interval Interval over which to debounce. The function will
400 * only be called after the full interval has elapsed since the last call.
401 * @param {SCOPE=} opt_scope Object in whose scope to call the function.
402 * @return {function(...?): undefined} Wrapped function.
403 * @template SCOPE
404 */
405 goog.functions.debounce = function(f, interval, opt_scope) {
406 var timeout = 0;
407 return /** @type {function(...?)} */ (function(var_args) {
408 goog.global.clearTimeout(timeout);
409 var args = arguments;
410 timeout = goog.global.setTimeout(function() {
411 f.apply(opt_scope, args);
412 }, interval);
413 });
414 };
415
416
417 /**
418 * Wraps a function to allow it to be called, at most, once per interval
419 * (specified in milliseconds). If the wrapper function is called N times in
420 * that interval, both the 1st and the Nth calls will go through.
421 *
422 * This is particularly useful for limiting repeated user requests where the
423 * the last action should win, but you also don't want to wait until the end of
424 * the interval before sending a request out, as it leads to a perception of
425 * slowness for the user.
426 *
427 * @param {function(this:SCOPE, ...?)} f Function to call.
428 * @param {number} interval Interval over which to throttle. The function can
429 * only be called once per interval.
430 * @param {SCOPE=} opt_scope Object in whose scope to call the function.
431 * @return {function(...?): undefined} Wrapped function.
432 * @template SCOPE
433 */
434 goog.functions.throttle = function(f, interval, opt_scope) {
435 var timeout = 0;
436 var shouldFire = false;
437 var args = [];
438
439 var handleTimeout = function() {
440 timeout = 0;
441 if (shouldFire) {
442 shouldFire = false;
443 fire();
444 }
445 };
446
447 var fire = function() {
448 timeout = goog.global.setTimeout(handleTimeout, interval);
449 f.apply(opt_scope, args);
450 };
451
452 return /** @type {function(...?)} */ (function(var_args) {
453 args = arguments;
454 if (!timeout) {
455 fire();
456 } else {
457 shouldFire = true;
458 }
459 });
460 };
461
462
463 /**
464 * Wraps a function to allow it to be called, at most, once per interval
465 * (specified in milliseconds). If the wrapper function is called N times within
466 * that interval, only the 1st call will go through.
467 *
468 * This is particularly useful for limiting repeated user requests where the
469 * first request is guaranteed to have all the data required to perform the
470 * final action, so there's no need to wait until the end of the interval before
471 * sending the request out.
472 *
473 * @param {function(this:SCOPE, ...?)} f Function to call.
474 * @param {number} interval Interval over which to rate-limit. The function will
475 * only be called once per interval, and ignored for the remainer of the
476 * interval.
477 * @param {SCOPE=} opt_scope Object in whose scope to call the function.
478 * @return {function(...?): undefined} Wrapped function.
479 * @template SCOPE
480 */
481 goog.functions.rateLimit = function(f, interval, opt_scope) {
482 var timeout = 0;
483
484 var handleTimeout = function() {
485 timeout = 0;
486 };
487
488 return /** @type {function(...?)} */ (function(var_args) {
489 if (!timeout) {
490 timeout = goog.global.setTimeout(handleTimeout, interval);
491 f.apply(opt_scope, arguments);
492 }
493 });
494 };