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.