iteratee.js 1.6 KB

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