before.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /** Used as the `TypeError` message for "Functions" methods. */
  2. var FUNC_ERROR_TEXT = 'Expected a function';
  3. /**
  4. * Creates a function that invokes `func`, with the `this` binding and arguments
  5. * of the created function, while it's called less than `n` times. Subsequent
  6. * calls to the created function return the result of the last `func` invocation.
  7. *
  8. * @static
  9. * @memberOf _
  10. * @category Function
  11. * @param {number} n The number of calls at which `func` is no longer invoked.
  12. * @param {Function} func The function to restrict.
  13. * @returns {Function} Returns the new restricted function.
  14. * @example
  15. *
  16. * jQuery('#add').on('click', _.before(5, addContactToList));
  17. * // => allows adding up to 4 contacts to the list
  18. */
  19. function before(n, func) {
  20. var result;
  21. if (typeof func != 'function') {
  22. if (typeof n == 'function') {
  23. var temp = n;
  24. n = func;
  25. func = temp;
  26. } else {
  27. throw new TypeError(FUNC_ERROR_TEXT);
  28. }
  29. }
  30. return function() {
  31. if (--n > 0) {
  32. result = func.apply(this, arguments);
  33. }
  34. if (n <= 1) {
  35. func = undefined;
  36. }
  37. return result;
  38. };
  39. }
  40. module.exports = before;