overArgs.js 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var apply = require('./_apply'),
  2. arrayMap = require('./_arrayMap'),
  3. baseFlatten = require('./_baseFlatten'),
  4. baseIteratee = require('./_baseIteratee'),
  5. baseRest = require('./_baseRest'),
  6. baseUnary = require('./_baseUnary'),
  7. castRest = require('./_castRest'),
  8. isArray = require('./isArray');
  9. /* Built-in method references for those with the same name as other `lodash` methods. */
  10. var nativeMin = Math.min;
  11. /**
  12. * Creates a function that invokes `func` with its arguments transformed.
  13. *
  14. * @static
  15. * @since 4.0.0
  16. * @memberOf _
  17. * @category Function
  18. * @param {Function} func The function to wrap.
  19. * @param {...(Function|Function[])} [transforms=[_.identity]]
  20. * The argument transforms.
  21. * @returns {Function} Returns the new function.
  22. * @example
  23. *
  24. * function doubled(n) {
  25. * return n * 2;
  26. * }
  27. *
  28. * function square(n) {
  29. * return n * n;
  30. * }
  31. *
  32. * var func = _.overArgs(function(x, y) {
  33. * return [x, y];
  34. * }, [square, doubled]);
  35. *
  36. * func(9, 3);
  37. * // => [81, 6]
  38. *
  39. * func(10, 5);
  40. * // => [100, 10]
  41. */
  42. var overArgs = castRest(function(func, transforms) {
  43. transforms = (transforms.length == 1 && isArray(transforms[0]))
  44. ? arrayMap(transforms[0], baseUnary(baseIteratee))
  45. : arrayMap(baseFlatten(transforms, 1), baseUnary(baseIteratee));
  46. var funcsLength = transforms.length;
  47. return baseRest(function(args) {
  48. var index = -1,
  49. length = nativeMin(args.length, funcsLength);
  50. while (++index < length) {
  51. args[index] = transforms[index].call(this, args[index]);
  52. }
  53. return apply(func, this, args);
  54. });
  55. });
  56. module.exports = overArgs;