"Let go of the thoughts that don't make you strong." —Unknown
/**
* 创建一个调用func的函数,通过this绑定和创建函数的参数调用func,调用次数不超过 n 次。
* 之后再调用这个函数,将返回一次最后调用func的结果。
*
* @since 3.0.0
* @category Function
* @param {number} n 限制调用func 的次数
* @param {Function} func 受限制执行的函数
* @returns {Function} 返回新的函数
*/
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;
}
return result;
};
}
let times = 0;
const newFunc = before(3, function() {
return ++times;
});
newFunc(); // n = 2, 执行传入func,return 1
newFunc(); // n = 1, 执行传入func,return 2
newFunc(); // n = 1, 不执行 func,return 2
newFunc(); // n = 1, 不执行 func,return 2