developer-plus / interview

https://interview.developer-plus.org
MIT License
9 stars 1 forks source link

once函数 => 简洁闭包版 #18

Closed ChenHaoJie9527 closed 2 years ago

ChenHaoJie9527 commented 2 years ago

function before(n, func) { let result if (typeof func !== 'function') { throw new TypeError('Expected a function') } return function(...args) { if (--n > 0) { result = func.apply(this, args) } if (n <= 1) { func = undefined } console.log('result', result); return result } } function once(func) { return before(2, func) } const res = once((arg) => arg); console.log('once', res(10)); console.log('once', res(2));

Hongbusi commented 2 years ago

感谢你的贡献~

不过更建议把答案更新到今天的题目评论下面,链接:https://github.com/developer-plus/interview/issues/17