before.js

  1. import defaultTo from './defaultTo';
  2. import { FUNC_ERROR_TEXT } from './internals/helpers';
  3. import { nativeUndefined } from './internals/native';
  4. import toNumber from './toNumber';
  5. /**
  6. * 创建一个调用 `func` 的函数,调用次数少于 `n` 次。之后再调用这个函数,将返回最后一次调用 `func` 的结果。
  7. *
  8. * @alias module:Function.before
  9. * @since 1.0.0
  10. * @param {number} n 不再调用 `func` 的次数。
  11. * @param {Function} func 限制执行的函数。
  12. * @returns {Function} 新的限定函数。
  13. * @example
  14. *
  15. * let count = 0;
  16. *
  17. * const increment = before(3, () => {
  18. * return ++count;
  19. * });
  20. *
  21. * increment(); // 1
  22. * increment(); // 2
  23. * increment(); // 2 返回之前的结果
  24. *
  25. */
  26. function before(n, func) {
  27. if (typeof func !== 'function') {
  28. throw new TypeError(FUNC_ERROR_TEXT);
  29. }
  30. let result;
  31. n = defaultTo(toNumber(n), 0);
  32. return function () {
  33. if (--n > 0) {
  34. // @ts-expect-error
  35. // eslint-disable-next-line prefer-rest-params
  36. result = func.apply(this, arguments);
  37. }
  38. if (n <= 1) {
  39. // @ts-expect-error
  40. func = nativeUndefined;
  41. }
  42. return result;
  43. };
  44. }
  45. export default before;