after.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /** Used as the `TypeError` message for "Functions" methods. */
  2. var FUNC_ERROR_TEXT = 'Expected a function';
  3. /* Native method references for those with the same name as other `lodash` methods. */
  4. var nativeIsFinite = global.isFinite;
  5. /**
  6. * The opposite of `_.before`; this method creates a function that invokes
  7. * `func` once it's called `n` or more times.
  8. *
  9. * @static
  10. * @memberOf _
  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. if (typeof n == 'function') {
  31. var temp = n;
  32. n = func;
  33. func = temp;
  34. } else {
  35. throw new TypeError(FUNC_ERROR_TEXT);
  36. }
  37. }
  38. n = nativeIsFinite(n = +n) ? n : 0;
  39. return function() {
  40. if (--n < 1) {
  41. return func.apply(this, arguments);
  42. }
  43. };
  44. }
  45. module.exports = after;