Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

函数memory #43

Open
18888628835 opened this issue Jun 12, 2021 · 0 comments
Open

函数memory #43

18888628835 opened this issue Jun 12, 2021 · 0 comments

Comments

@18888628835
Copy link
Owner

18888628835 commented Jun 12, 2021

函数memory

函数 memory(函数记忆)可以理解为当执行某个函数时,先把它的返回值记下来,当下次函数执行,如果传递的参数相同时,则直接返回记忆的返回值,而不是重新执行一遍函数。

function add(a,b){
  return a+b
}
// 假设 memorize 可以实现让传入的函数记忆
const memorizedAdd = memorize(add);

console.log(memorizedAdd(1, 2))//第一次时返回3,并将结果记下来
console.log(memorizedAdd(1, 2)) //第二次时不进行 a+b 操作,而是直接将第一次的结果3记下来

要实现这样的memorize函数非常简单,还是熟悉的配方,使用闭包。

function memorize(func) {
  let cache = {}
  return function(...rest) {
    let key = rest.join('-')
    if (cache[key]) {
      console.log('第二次执行到缓存')
      return cache[key]
    } else {
      console.log('第一次执行,做缓存处理')
      cache[key] = func(...rest)
      return cache[key]
    }
  }
}

我们来检查一下

console.log(memorizedAdd(1, 2))
//"第一次执行,做缓存处理"
//3
console.log(memorizedAdd(1, 2))
//"第二次执行到缓存"
//3

函数memory更多的是一种编程技巧,其实概念非常简单,适用场景在于如果你需要进行大量的重复计算,那么可以采取函数memory的方式来缓存数据。

面试题

这里有一道关于 memory 函数的面试题

const memo = (fn) => {
  请补全
}
const x2 = memo((x) => {
    console.log('执行了一次')
    return x * 2
  })
  // 第一次调用 x2(1)
console.log(x2(1)) // 打印出执行了,并且返回2
  // 第二次调用 x2(1)
console.log(x2(1)) // 不打印执行,并且返回上次的结果2
  // 第三次调用 x2(1)
console.log(x2(1)) // 不打印执行,并且返回上次的结果2

思路整理:

1、看调用方式,可以得出memo调用后返回一个函数

2、采用闭包的形式来做记录即可,返回记录的结果即可

const memo = (fn) => {
  //请补全
  const cache = {}
  return function(...rest) {
    const key = rest
    if (cache[key]) {
      return cache[key]
    } else {
      return cache[key] = fn(...rest)
    }
  }
}

结束~

enjoy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant