diff options
Diffstat (limited to 'lib/memoize.js')
-rw-r--r-- | lib/memoize.js | 31 |
1 files changed, 10 insertions, 21 deletions
diff --git a/lib/memoize.js b/lib/memoize.js index ea0da43..d800106 100644 --- a/lib/memoize.js +++ b/lib/memoize.js @@ -1,13 +1,7 @@ -import identity from './internal/identity'; -import slice from './internal/slice'; import setImmediate from './internal/setImmediate'; import initialParams from './internal/initialParams'; import wrapAsync from './internal/wrapAsync'; -function has(obj, key) { - return key in obj; -} - /** * Caches the results of an async function. When creating a hash to store * function results against, the callback is omitted from the hash and an @@ -48,34 +42,29 @@ function has(obj, key) { * // callback * }); */ -export default function memoize(fn, hasher) { +export default function memoize(fn, hasher = v => v) { var memo = Object.create(null); var queues = Object.create(null); - hasher = hasher || identity; var _fn = wrapAsync(fn); - var memoized = initialParams(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - setImmediate(function() { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate(() => callback(null, ...memo[key])); + } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; - _fn.apply(null, args.concat(function(/*args*/) { - var args = slice(arguments); - var err = args[0]; + _fn(...args, (err, ...resultArgs) => { // #1465 don't memoize if an error occurred if (!err) { - memo[key] = args; + memo[key] = resultArgs; } var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); + q[i](err, ...resultArgs); } - })); + }); } }); memoized.memo = memo; |