Skip to content

Instantly share code, notes, and snippets.

@headquarters
Last active July 28, 2018 19:10
Show Gist options
  • Select an option

  • Save headquarters/f08274b00d0829c22caed8cf8bac4755 to your computer and use it in GitHub Desktop.

Select an option

Save headquarters/f08274b00d0829c22caed8cf8bac4755 to your computer and use it in GitHub Desktop.
Memoization in JavaScript using ES6 structures
function memoize(fn) {
let state = {};
return function() {
const args = [...arguments];
if(state[args]) {
return state[args];
} else {
const value = fn.apply(this, args);
state[args] = value;
return value;
}
}
}
function add(a, b) {
console.log('adding', a, b);
return a + b;
}
const memoizedAdd = memoize(add);
console.log(memoizedAdd(1, 2));
// adding 1 2
// 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment