implement `_.once()`【BFE.dev】

No.46 question of BFE.dev, link here implement _.once().

function func(num) {
  return num
}

const onced = once(func)

onced(1) 
// 1, func called with 1

onced(2)
// 1, even 2 is passed, previous result is returned

we can see the code this question provides, first it pushed func into once, and once returned a funtion called onced, then it called onced and pushed 1 into it and get 1 as result, it called onced again and pushed 2, but still got the first time result.

So it’s actually a simple question, we can implement it easily, first we need to initialize a result which is equals to null and isCall which is equals to false. Then return a function, and take in spreaded args as parameters.

Then we check if isCall is true, if so, it means the function had been called, so just return result, if not, assign func.call(this, …args) to result, and change isCall’s status, finally return result.

function once(func) {
  let result = null
  let isCall = false
  return function (...args) {
    if (isCall) {
      return result
    }
    result = func.call(this, ...args)
    isCall = true
    return result
  }
}

And that’s all process to implement this function, hope it helpful.

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值