repl.it
@cjjenkinson/

memoize

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const memoize = (func) => {
  var result = {}; 
  
  return function () {
    var args = Array.prototype.slice.call(arguments);

    if (args in result) {
    	console.log('Result has already been computed...')
      return result[args];
    } else {
      return result[args] = func.apply(this, args);
    }
  };
}

const multByTwo = (num) => {
  return num * 2;
}

var memoized = memoize(multByTwo);

var result = memoized(5);
console.log(result);
// => 10;

var resultDuplicate = memoized(5);
console.log(resultDuplicate);
// => Result has already been computed...
Native Browser JavaScript