Skip to content

Commit

Permalink
feat: Add memoize function in utils
Browse files Browse the repository at this point in the history
  • Loading branch information
lojjic committed Feb 20, 2020
1 parent 0708fdb commit 16efb01
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/troika-core/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 16efb01

Please sign in to comment.