UNPKG

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