before
在达到n次之前,每次都正常执行,第n次不执行
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
}
}
略去条件判断代码,重写部分逻辑:
function before(n, func) {
let result, count = n;
return function(...args) {
count = count - 1
if (count > 0) result = func.apply(this, args)
if (count <= 1) func = undefined
return result
}
}
after
只有到n次(以及n次之后)的时候才执行,n之前的都不执行。n小于等于1时,与普通函数行为无异
function after(n, func) {
if (typeof func !== 'function') {
throw new TypeError('Expected a function')
}
n = n || 0
return function(...args) {
if (--n < 1) {
return func.apply(this, args)
}
}
}
略去条件判断代码,重写部分逻辑:
function after(n, func) {
let count = n || 0
return function(...args) {
count = count - 1
if (count < 1) return func.apply(this, args)
}
}