-1

I was looking into memoization and it simply confuses me. I've been trying to work on this example but I can't help but understand it quite clearly. This is what I came up with.

function memoize(x) {
    //var x = [] 
    check = function() { 
    return copycat(x,x)
 }
   return x;
}

function copycat(input,output) {
   if (input === input || output === output) {
   return ""
   }
}

The goal was to input these 3 lines into the console of my browser:

function square(x) { alert("computed sq " + x); return x * x; }

msq = memoize(square)

msq(2) + msq(2) + msq(3)

It was display: computed sq 2 and then computed sq 3. It ignores the reoccurence of msq(2) but still computes the return result, which is 17. I'm really lost in how to approach this :( any help?

Community
  • 1
  • 1
stoiven
  • 31
  • 7
  • 1
    B.T.W.: Your function doesn't ignore the reoccurence of msq(2) at all. It calls it a second time. All your memoize function does is create a new function called `check`, does absolutely nothing with it, and then returns the exact original function that memoize was called with. – Gerrat Feb 18 '15 at 03:24
  • This doesn't strike me as a particularly constructive comment. Maybe try offering an answer that explains how a proper memoize function is supposed to work? – Kevin Ennis Feb 18 '15 at 03:34

1 Answers1

3

Here's a very basic memoize function:

function memoize( fn ) {
  var cache = {};
  return function( arg ) {
    if ( !cache[ arg ] ) {
      cache[ arg ] = fn( arg );
    }
    return cache[ arg ];
  }
}

This works by accepting a function and returning a new function that can be called in its place.

When you call the memoized version, it will check to see if it has a saved result. If it does, it will return it. Otherwise, it'll run your original function, save the result, and then return it.

Here's an example:

function slow( n ) {
  for ( var i = 0; i < 1e9; ++i ) {
    i;
  }
  return n * n;
}

var mem = memoize( slow );

mem( 10 );
mem( 10 );

If you play with that in the console, you'll notice that the first call to mem( 10 ) takes a little while. The next one (and all subsequent calls) execute very quickly.

Kevin Ennis
  • 14,226
  • 2
  • 43
  • 44