From 16efb013eb62bb3630b0375ad7a054820aa2382c Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Wed, 19 Feb 2020 21:04:30 -0700 Subject: [PATCH] feat: Add memoize function in utils --- packages/troika-core/src/utils.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/packages/troika-core/src/utils.js b/packages/troika-core/src/utils.js index 20e4822e..4bbaf71b 100644 --- a/packages/troika-core/src/utils.js +++ b/packages/troika-core/src/utils.js @@ -105,6 +105,34 @@ export const getIdForObject = (() => { })() +/** + * Create a function that memoizes the result of another function based on the most + * recent call's arguments and `this`. The arguments are compared using strict shallow equality. + * @param {function} fn + * @return {function} + */ +export function memoize(fn) { + let prevArgs, prevThis, prevResult + return function() { + let changed = !prevArgs || this !== prevThis || arguments.length !== prevArgs.length + if (!changed) { + for (let i = 0, len = arguments.length; i < len; i++) { + if (arguments[i] !== prevArgs[i]) { + changed = true + break + } + } + } + if (changed) { + prevArgs = Array.prototype.slice.call(arguments) + prevThis = this + prevResult = fn.apply(this, arguments) + } + return prevResult + } +} + + /** * Utility for the "extend-as" pattern used in several places to decorate facade * classes with extra capabilities.