every.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var arrayEvery = require('./_arrayEvery'),
  2. baseEvery = require('./_baseEvery'),
  3. baseIteratee = require('./_baseIteratee'),
  4. isArray = require('./isArray'),
  5. isIterateeCall = require('./_isIterateeCall');
  6. /**
  7. * Checks if `predicate` returns truthy for **all** elements of `collection`.
  8. * Iteration is stopped once `predicate` returns falsey. The predicate is
  9. * invoked with three arguments: (value, index|key, collection).
  10. *
  11. * **Note:** This method returns `true` for
  12. * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
  13. * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
  14. * elements of empty collections.
  15. *
  16. * @static
  17. * @memberOf _
  18. * @since 0.1.0
  19. * @category Collection
  20. * @param {Array|Object} collection The collection to iterate over.
  21. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  22. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  23. * @returns {boolean} Returns `true` if all elements pass the predicate check,
  24. * else `false`.
  25. * @example
  26. *
  27. * _.every([true, 1, null, 'yes'], Boolean);
  28. * // => false
  29. *
  30. * var users = [
  31. * { 'user': 'barney', 'age': 36, 'active': false },
  32. * { 'user': 'fred', 'age': 40, 'active': false }
  33. * ];
  34. *
  35. * // The `_.matches` iteratee shorthand.
  36. * _.every(users, { 'user': 'barney', 'active': false });
  37. * // => false
  38. *
  39. * // The `_.matchesProperty` iteratee shorthand.
  40. * _.every(users, ['active', false]);
  41. * // => true
  42. *
  43. * // The `_.property` iteratee shorthand.
  44. * _.every(users, 'active');
  45. * // => false
  46. */
  47. function every(collection, predicate, guard) {
  48. var func = isArray(collection) ? arrayEvery : baseEvery;
  49. if (guard && isIterateeCall(collection, predicate, guard)) {
  50. predicate = undefined;
  51. }
  52. return func(collection, baseIteratee(predicate, 3));
  53. }
  54. module.exports = every;