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.

40 lines
1.1 KiB

4 years ago
  1. /** Error message constants. */
  2. var FUNC_ERROR_TEXT = 'Expected a function';
  3. /**
  4. * Creates a function that negates the result of the predicate `func`. The
  5. * `func` predicate is invoked with the `this` binding and arguments of the
  6. * created function.
  7. *
  8. * @static
  9. * @memberOf _
  10. * @since 3.0.0
  11. * @category Function
  12. * @param {Function} predicate The predicate to negate.
  13. * @returns {Function} Returns the new negated function.
  14. * @example
  15. *
  16. * function isEven(n) {
  17. * return n % 2 == 0;
  18. * }
  19. *
  20. * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
  21. * // => [1, 3, 5]
  22. */
  23. function negate(predicate) {
  24. if (typeof predicate != 'function') {
  25. throw new TypeError(FUNC_ERROR_TEXT);
  26. }
  27. return function() {
  28. var args = arguments;
  29. switch (args.length) {
  30. case 0: return !predicate.call(this);
  31. case 1: return !predicate.call(this, args[0]);
  32. case 2: return !predicate.call(this, args[0], args[1]);
  33. case 3: return !predicate.call(this, args[0], args[1], args[2]);
  34. }
  35. return !predicate.apply(this, args);
  36. };
  37. }
  38. module.exports = negate;