UNPKG

2.37 kBJavaScriptView Raw
1'use strict'; // function utils
2
3/**
4 * Memoize a given function by caching the computed result.
5 * The cache of a memoized function can be cleared by deleting the `cache`
6 * property of the function.
7 *
8 * @param {function} fn The function to be memoized.
9 * Must be a pure function.
10 * @param {function(args: Array)} [hasher] A custom hash builder.
11 * Is JSON.stringify by default.
12 * @return {function} Returns the memoized function
13 */
14
15function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
16
17exports.memoize = function (fn, hasher) {
18 return function memoize() {
19 if (_typeof(memoize.cache) !== 'object') {
20 memoize.cache = {};
21 }
22
23 var args = [];
24
25 for (var i = 0; i < arguments.length; i++) {
26 args[i] = arguments[i];
27 }
28
29 var hash = hasher ? hasher(args) : JSON.stringify(args);
30
31 if (!(hash in memoize.cache)) {
32 memoize.cache[hash] = fn.apply(fn, args);
33 }
34
35 return memoize.cache[hash];
36 };
37};
38/**
39 * Find the maximum number of arguments expected by a typed function.
40 * @param {function} fn A typed function
41 * @return {number} Returns the maximum number of expected arguments.
42 * Returns -1 when no signatures where found on the function.
43 */
44
45
46exports.maxArgumentCount = function (fn) {
47 return Object.keys(fn.signatures || {}).reduce(function (args, signature) {
48 var count = (signature.match(/,/g) || []).length + 1;
49 return Math.max(args, count);
50 }, -1);
51};
52/**
53 * Call a typed function with the
54 * @param {function} fn A function or typed function
55 * @return {number} Returns the maximum number of expected arguments.
56 * Returns -1 when no signatures where found on the function.
57 */
58
59
60exports.callWithRightArgumentCount = function (fn, args, argCount) {
61 return Object.keys(fn.signatures || {}).reduce(function (args, signature) {
62 var count = (signature.match(/,/g) || []).length + 1;
63 return Math.max(args, count);
64 }, -1);
65};
\No newline at end of file