简体   繁体   English

在 JavaScript 中实现一个记忆功能

[英]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.这是一个练习,因为 memoize 函数不需要记住所有先前的值,只需要最后一个输入值和函数返回。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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