overArgs.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var apply = require('./_apply'),
  2. arrayMap = require('./_arrayMap'),
  3. baseFlatten = require('./_baseFlatten'),
  4. baseIteratee = require('./_baseIteratee'),
  5. baseUnary = require('./_baseUnary'),
  6. isArray = require('./isArray'),
  7. isFlattenableIteratee = require('./_isFlattenableIteratee'),
  8. rest = require('./rest');
  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 arguments transformed by
  13. * corresponding `transforms`.
  14. *
  15. * @static
  16. * @since 4.0.0
  17. * @memberOf _
  18. * @category Function
  19. * @param {Function} func The function to wrap.
  20. * @param {...(Array|Array[]|Function|Function[]|Object|Object[]|string|string[])}
  21. * [transforms[_.identity]] The functions to transform.
  22. * @returns {Function} Returns the new function.
  23. * @example
  24. *
  25. * function doubled(n) {
  26. * return n * 2;
  27. * }
  28. *
  29. * function square(n) {
  30. * return n * n;
  31. * }
  32. *
  33. * var func = _.overArgs(function(x, y) {
  34. * return [x, y];
  35. * }, [square, doubled]);
  36. *
  37. * func(9, 3);
  38. * // => [81, 6]
  39. *
  40. * func(10, 5);
  41. * // => [100, 10]
  42. */
  43. var overArgs = rest(function(func, transforms) {
  44. transforms = (transforms.length == 1 && isArray(transforms[0]))
  45. ? arrayMap(transforms[0], baseUnary(baseIteratee))
  46. : arrayMap(baseFlatten(transforms, 1, isFlattenableIteratee), baseUnary(baseIteratee));
  47. var funcsLength = transforms.length;
  48. return rest(function(args) {
  49. var index = -1,
  50. length = nativeMin(args.length, funcsLength);
  51. while (++index < length) {
  52. args[index] = transforms[index].call(this, args[index]);
  53. }
  54. return apply(func, this, args);
  55. });
  56. });
  57. module.exports = overArgs;