modArgs.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var arrayEvery = require('../internal/arrayEvery'),
  2. baseFlatten = require('../internal/baseFlatten'),
  3. baseIsFunction = require('../internal/baseIsFunction'),
  4. restParam = require('./restParam');
  5. /** Used as the `TypeError` message for "Functions" methods. */
  6. var FUNC_ERROR_TEXT = 'Expected a function';
  7. /* Native method references for those with the same name as other `lodash` methods. */
  8. var nativeMin = Math.min;
  9. /**
  10. * Creates a function that runs each argument through a corresponding
  11. * transform function.
  12. *
  13. * @static
  14. * @memberOf _
  15. * @category Function
  16. * @param {Function} func The function to wrap.
  17. * @param {...(Function|Function[])} [transforms] The functions to transform
  18. * arguments, specified as individual functions or arrays of functions.
  19. * @returns {Function} Returns the new function.
  20. * @example
  21. *
  22. * function doubled(n) {
  23. * return n * 2;
  24. * }
  25. *
  26. * function square(n) {
  27. * return n * n;
  28. * }
  29. *
  30. * var modded = _.modArgs(function(x, y) {
  31. * return [x, y];
  32. * }, square, doubled);
  33. *
  34. * modded(1, 2);
  35. * // => [1, 4]
  36. *
  37. * modded(5, 10);
  38. * // => [25, 20]
  39. */
  40. var modArgs = restParam(function(func, transforms) {
  41. transforms = baseFlatten(transforms);
  42. if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
  43. throw new TypeError(FUNC_ERROR_TEXT);
  44. }
  45. var length = transforms.length;
  46. return restParam(function(args) {
  47. var index = nativeMin(args.length, length);
  48. while (index--) {
  49. args[index] = transforms[index](args[index]);
  50. }
  51. return func.apply(this, args);
  52. });
  53. });
  54. module.exports = modArgs;