You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.0 KiB

4 years ago
  1. var toInteger = require('./toInteger');
  2. /** Error message constants. */
  3. var FUNC_ERROR_TEXT = 'Expected a function';
  4. /**
  5. * The opposite of `_.before`; this method creates a function that invokes
  6. * `func` once it's called `n` or more times.
  7. *
  8. * @static
  9. * @memberOf _
  10. * @since 0.1.0
  11. * @category Function
  12. * @param {number} n The number of calls before `func` is invoked.
  13. * @param {Function} func The function to restrict.
  14. * @returns {Function} Returns the new restricted function.
  15. * @example
  16. *
  17. * var saves = ['profile', 'settings'];
  18. *
  19. * var done = _.after(saves.length, function() {
  20. * console.log('done saving!');
  21. * });
  22. *
  23. * _.forEach(saves, function(type) {
  24. * asyncSave({ 'type': type, 'complete': done });
  25. * });
  26. * // => Logs 'done saving!' after the two async saves have completed.
  27. */
  28. function after(n, func) {
  29. if (typeof func != 'function') {
  30. throw new TypeError(FUNC_ERROR_TEXT);
  31. }
  32. n = toInteger(n);
  33. return function() {
  34. if (--n < 1) {
  35. return func.apply(this, arguments);
  36. }
  37. };
  38. }
  39. module.exports = after;