nAry.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import _curry2 from "./internal/_curry2.js";
  2. /**
  3. * Wraps a function of any arity (including nullary) in a function that accepts
  4. * exactly `n` parameters. Any extraneous parameters will not be passed to the
  5. * supplied function.
  6. *
  7. * @func
  8. * @memberOf R
  9. * @since v0.1.0
  10. * @category Function
  11. * @sig Number -> (* -> a) -> (* -> a)
  12. * @param {Number} n The desired arity of the new function.
  13. * @param {Function} fn The function to wrap.
  14. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
  15. * arity `n`.
  16. * @see R.binary, R.unary
  17. * @example
  18. *
  19. * const takesTwoArgs = (a, b) => [a, b];
  20. *
  21. * takesTwoArgs.length; //=> 2
  22. * takesTwoArgs(1, 2); //=> [1, 2]
  23. *
  24. * const takesOneArg = R.nAry(1, takesTwoArgs);
  25. * takesOneArg.length; //=> 1
  26. * // Only `n` arguments are passed to the wrapped function
  27. * takesOneArg(1, 2); //=> [1, undefined]
  28. * @symb R.nAry(0, f)(a, b) = f()
  29. * @symb R.nAry(1, f)(a, b) = f(a)
  30. * @symb R.nAry(2, f)(a, b) = f(a, b)
  31. */
  32. var nAry =
  33. /*#__PURE__*/
  34. _curry2(function nAry(n, fn) {
  35. switch (n) {
  36. case 0:
  37. return function () {
  38. return fn.call(this);
  39. };
  40. case 1:
  41. return function (a0) {
  42. return fn.call(this, a0);
  43. };
  44. case 2:
  45. return function (a0, a1) {
  46. return fn.call(this, a0, a1);
  47. };
  48. case 3:
  49. return function (a0, a1, a2) {
  50. return fn.call(this, a0, a1, a2);
  51. };
  52. case 4:
  53. return function (a0, a1, a2, a3) {
  54. return fn.call(this, a0, a1, a2, a3);
  55. };
  56. case 5:
  57. return function (a0, a1, a2, a3, a4) {
  58. return fn.call(this, a0, a1, a2, a3, a4);
  59. };
  60. case 6:
  61. return function (a0, a1, a2, a3, a4, a5) {
  62. return fn.call(this, a0, a1, a2, a3, a4, a5);
  63. };
  64. case 7:
  65. return function (a0, a1, a2, a3, a4, a5, a6) {
  66. return fn.call(this, a0, a1, a2, a3, a4, a5, a6);
  67. };
  68. case 8:
  69. return function (a0, a1, a2, a3, a4, a5, a6, a7) {
  70. return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);
  71. };
  72. case 9:
  73. return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
  74. return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);
  75. };
  76. case 10:
  77. return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
  78. return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
  79. };
  80. default:
  81. throw new Error('First argument to nAry must be a non-negative integer no greater than ten');
  82. }
  83. });
  84. export default nAry;