before

Each execution is normal until it reaches the NTH, and the NTH is not executed

function before(n, func) {
  let result
  if (typeoffunc ! = ='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
  }
}
Copy the code

Omit the conditional code and rewrite part of the logic:

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
  }
}
Copy the code

after

Only up to n times (and after n times), not up to n times. When n is less than or equal to 1, it behaves like a normal function

function after(n, func) {
  if (typeoffunc ! = ='function') {
    throw new TypeError('Expected a function')
  }
  n = n || 0
  return function(. args) {
    if (--n < 1) {
      return func.apply(this, args)
    }
  }
}
Copy the code

Omit the conditional code and rewrite part of the logic:

function after(n, func) {
  let count = n || 0
  return function(. args) {
    count = count - 1
    if (count < 1) return func.apply(this, args)
  }
}
Copy the code