every.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var arrayEvery = require('../internal/arrayEvery'),
  2. baseCallback = require('../internal/baseCallback'),
  3. baseEvery = require('../internal/baseEvery'),
  4. isArray = require('../lang/isArray'),
  5. isIterateeCall = require('../internal/isIterateeCall');
  6. /**
  7. * Checks if `predicate` returns truthy for **all** elements of `collection`.
  8. * The predicate is bound to `thisArg` and invoked with three arguments:
  9. * (value, index|key, collection).
  10. *
  11. * If a property name is provided for `predicate` the created `_.property`
  12. * style callback returns the property value of the given element.
  13. *
  14. * If a value is also provided for `thisArg` the created `_.matchesProperty`
  15. * style callback returns `true` for elements that have a matching property
  16. * value, else `false`.
  17. *
  18. * If an object is provided for `predicate` the created `_.matches` style
  19. * callback returns `true` for elements that have the properties of the given
  20. * object, else `false`.
  21. *
  22. * @static
  23. * @memberOf _
  24. * @alias all
  25. * @category Collection
  26. * @param {Array|Object|string} collection The collection to iterate over.
  27. * @param {Function|Object|string} [predicate=_.identity] The function invoked
  28. * per iteration.
  29. * @param {*} [thisArg] The `this` binding of `predicate`.
  30. * @returns {boolean} Returns `true` if all elements pass the predicate check,
  31. * else `false`.
  32. * @example
  33. *
  34. * _.every([true, 1, null, 'yes'], Boolean);
  35. * // => false
  36. *
  37. * var users = [
  38. * { 'user': 'barney', 'active': false },
  39. * { 'user': 'fred', 'active': false }
  40. * ];
  41. *
  42. * // using the `_.matches` callback shorthand
  43. * _.every(users, { 'user': 'barney', 'active': false });
  44. * // => false
  45. *
  46. * // using the `_.matchesProperty` callback shorthand
  47. * _.every(users, 'active', false);
  48. * // => true
  49. *
  50. * // using the `_.property` callback shorthand
  51. * _.every(users, 'active');
  52. * // => false
  53. */
  54. function every(collection, predicate, thisArg) {
  55. var func = isArray(collection) ? arrayEvery : baseEvery;
  56. if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
  57. predicate = undefined;
  58. }
  59. if (typeof predicate != 'function' || thisArg !== undefined) {
  60. predicate = baseCallback(predicate, thisArg, 3);
  61. }
  62. return func(collection, predicate);
  63. }
  64. module.exports = every;