function/before.jsjavascript
/**
* 创建一个最多执行指定次数的函数,之后始终返回最近一次结果。
* @function before
* @memberof module:function
* @param {number} count 最大执行次数
* @param {Function} fn 目标函数
* @returns {Function} 限次包装函数
* @throws {TypeError|RangeError} 参数类型或 count 不合法时抛出
*/
function before(count, fn) {
if (!Number.isInteger(count) || count < 1) throw new RangeError('count must be a positive integer')
if (typeof fn !== 'function') throw new TypeError('fn must be a function')
let calls = 0
let result
return function (...args) {
if (calls < count) {
calls += 1
result = fn.apply(this, args)
}
return result
}
}
export default before