function/once.jsjavascript
/**
* 创建一个最多执行一次的函数。首次调用会保留调用方的 this 和全部参数;后续调用返回 undefined。
* @function once
* @memberof module:function
* @param {Function} fn 要包装的函数
* @returns {Function} 只能执行一次的函数
* @throws {TypeError} fn 不是函数时抛出
*/
function once(fn) {
if (typeof fn !== 'function') {
throw new TypeError('fn must be a function')
}
let called = false
let result
return function (...args) {
if (called) return result
called = true
result = fn.apply(this, args)
return result
}
}
export default once