callback.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var baseCallback = require('../internal/baseCallback'),
  2. isIterateeCall = require('../internal/isIterateeCall'),
  3. isObjectLike = require('../internal/isObjectLike'),
  4. matches = require('./matches');
  5. /**
  6. * Creates a function that invokes `func` with the `this` binding of `thisArg`
  7. * and arguments of the created function. If `func` is a property name the
  8. * created callback returns the property value for a given element. If `func`
  9. * is an object the created callback returns `true` for elements that contain
  10. * the equivalent object properties, otherwise it returns `false`.
  11. *
  12. * @static
  13. * @memberOf _
  14. * @alias iteratee
  15. * @category Utility
  16. * @param {*} [func=_.identity] The value to convert to a callback.
  17. * @param {*} [thisArg] The `this` binding of `func`.
  18. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
  19. * @returns {Function} Returns the callback.
  20. * @example
  21. *
  22. * var users = [
  23. * { 'user': 'barney', 'age': 36 },
  24. * { 'user': 'fred', 'age': 40 }
  25. * ];
  26. *
  27. * // wrap to create custom callback shorthands
  28. * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
  29. * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
  30. * if (!match) {
  31. * return callback(func, thisArg);
  32. * }
  33. * return function(object) {
  34. * return match[2] == 'gt'
  35. * ? object[match[1]] > match[3]
  36. * : object[match[1]] < match[3];
  37. * };
  38. * });
  39. *
  40. * _.filter(users, 'age__gt36');
  41. * // => [{ 'user': 'fred', 'age': 40 }]
  42. */
  43. function callback(func, thisArg, guard) {
  44. if (guard && isIterateeCall(func, thisArg, guard)) {
  45. thisArg = undefined;
  46. }
  47. return isObjectLike(func)
  48. ? matches(func)
  49. : baseCallback(func, thisArg);
  50. }
  51. module.exports = callback;