-2

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.

  • do you have some examples? what results do you expect? – Nina Scholz Jun 19 '22 at 17:53
  • Is this only for functions that expect two arguments? In your code you just forgot to do `valOne = x; valTwo = y;` in the `else` block. – trincot Jun 19 '22 at 17:57
  • What's the question? Consult the [help] articles for guidelines, especially "[ask]". See also "[How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/q/261592/90527)". – outis Jan 14 '23 at 09:28

1 Answers1

0

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));
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
  • I noticed that I wasn't updating the values which are supposed to record. Your code works perfectly, I get a bit lost because you omitted completely the line ```const memoize = (funct) =>``` So, I'm seeing that in this case isn't necessary. A lot more to learn. Thks. – Armando Endzelis Jun 19 '22 at 18:23