Skip to content
Advertisement

implement a memoization function in JavaScript [closed]

The function that I need to implement should take a function to memoize, then return a new function that remembers the inputs to the supplied function.

This is an exercise, for such is not required for the memoize function to remember all previous values, just the last input value, and the function return.

function memoizeTransform(f) {
  // valOne & valTwo intend to record the input values
  // of the function
  let valOne
  let valTwo
  // lastResult intend to record the result value of the function
  let lastResult
  const memoize = (funct) => (x1, x2) => {
    if (valOne === x1 && valTwo === x2) {
      console.log("if statement")
      return lastResult
    } else {
      lastResult = funct(x1, x2)
      return lastResult
    }
  }
  return memoize(f)
}

The actual code is not capable of accessing the previous values that I’m trying to record.

Advertisement

Answer

probably you’re looking for something like this:

function memoizeTransform(f) {
  let valOne;
  let valTwo;
  let lastResult;
  return (x1, x2) => {
    if (valOne === x1 && valTwo === x2) {
      console.log("Cached...");
      return lastResult;
    } else {
      lastResult = f(x1, x2);
      valOne = x1;
      valTwo = x2;
      return lastResult;
    }
  };
}

function sum(a, b) {
  console.log('Calculating...');
  return a + b;
}

let f = memoizeTransform(sum);
console.log(f(1, 2));
console.log(f(1, 2));
console.log(f(2, 3));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement