This solution uses a simple hash for holding stringified args to quickly lookup the cache.
The assumption is that only one type of function signature is ever used.
describe("Solution", function(){ var called = 0; function sum(a, b) { called++; return a + b; } it("should add 1 + 2", function(){ Test.assertEquals(memoize(sum)(1,2), 3); }); it("should have been called once", function(){ Test.assertEquals(called, 1); }); it("should still have been called once due to cache", function(){ memoize(sum)(1,2) Test.assertEquals(called, 1); }); it("should still have been called twice if different param orders", function(){ memoize(sum)(2,1) Test.assertEquals(called, 2); }); });
- describe("Solution", function(){
- var called = 0;
- function sum(a, b) {
- called++;
- return a + b;
- }
- it("should add 1 + 2", function(){
- Test.assertEquals(memoize(sum)(1,2), 3);
- });
- it("should have been called once", function(){
- Test.assertEquals(called, 1);
- });
- it("should still have been called once due to cache", function(){
- memoize(sum)(1,2)
- Test.assertEquals(called, 1);
- });
- it("should still have been called twice if different param orders", function(){
- memoize(sum)(2,1)
- Test.assertEquals(called, 2);
- });
- });
This solution uses a simple hash for holding stringified args to quickly lookup the cache.
The assumption is that only one type of function signature is ever used.
var lookup = {}; function memoize(func) { return (...args) => { // check cache hit if (!lookup[args.toString()]) { lookup[args.toString()] = func.apply(this, args); } return lookup[args.toString()]; }; }
- var lookup = {};
- function memoize(func) {
- return (...args) => {
// your function- // check cache hit
- if (!lookup[args.toString()]) {
- lookup[args.toString()] = func.apply(this, args);
- }
- return lookup[args.toString()];
- };
- }