简体   繁体   中英

implement a memoization function in JavaScript

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM