iteratee.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var baseClone = require('./_baseClone'),
  2. baseIteratee = require('./_baseIteratee');
  3. /** Used to compose bitmasks for cloning. */
  4. var CLONE_DEEP_FLAG = 1;
  5. /**
  6. * Creates a function that invokes `func` with the arguments of the created
  7. * function. If `func` is a property name, the created function returns the
  8. * property value for a given element. If `func` is an array or object, the
  9. * created function returns `true` for elements that contain the equivalent
  10. * source properties, otherwise it returns `false`.
  11. *
  12. * @static
  13. * @since 4.0.0
  14. * @memberOf _
  15. * @category Util
  16. * @param {*} [func=_.identity] The value to convert to a callback.
  17. * @returns {Function} Returns the callback.
  18. * @example
  19. *
  20. * var users = [
  21. * { 'user': 'barney', 'age': 36, 'active': true },
  22. * { 'user': 'fred', 'age': 40, 'active': false }
  23. * ];
  24. *
  25. * // The `_.matches` iteratee shorthand.
  26. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
  27. * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
  28. *
  29. * // The `_.matchesProperty` iteratee shorthand.
  30. * _.filter(users, _.iteratee(['user', 'fred']));
  31. * // => [{ 'user': 'fred', 'age': 40 }]
  32. *
  33. * // The `_.property` iteratee shorthand.
  34. * _.map(users, _.iteratee('user'));
  35. * // => ['barney', 'fred']
  36. *
  37. * // Create custom iteratee shorthands.
  38. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  39. * return !_.isRegExp(func) ? iteratee(func) : function(string) {
  40. * return func.test(string);
  41. * };
  42. * });
  43. *
  44. * _.filter(['abc', 'def'], /ef/);
  45. * // => ['def']
  46. */
  47. function iteratee(func) {
  48. return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
  49. }
  50. module.exports = iteratee;