# 实现一个 once 函数,记忆返回结果只执行一次

Issue

欢迎在 Issue 中交流与讨论: Issue 406 (opens new window)

简单实现如下:

function once (f) {
  let result
  let revoked = false
  
  return (...args) => {
    if (revoked) return result
    const r = f(...args)
    revoked = true
    result = r
    return r
  }
}
> const f = () => {console.log('call'); return 3;}
< undefined

> once_f = once(f)
< (...args) => {
    if (revoked) return result
    const r = f(...args)
    revoked = true
    result = r
  }

// 第一次调用
> once_f()
< call
< 3

// 第二次调用,没有打印 call
> once_f()
< 3
Last Updated: 1/17/2021, 2:02:56 PM