constructN.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import _curry2 from "./internal/_curry2.js";
  2. import curry from "./curry.js";
  3. import nAry from "./nAry.js";
  4. /**
  5. * Wraps a constructor function inside a curried function that can be called
  6. * with the same arguments and returns the same type. The arity of the function
  7. * returned is specified to allow using variadic constructor functions.
  8. *
  9. * @func
  10. * @memberOf R
  11. * @since v0.4.0
  12. * @category Function
  13. * @sig Number -> (* -> {*}) -> (* -> {*})
  14. * @param {Number} n The arity of the constructor function.
  15. * @param {Function} Fn The constructor function to wrap.
  16. * @return {Function} A wrapped, curried constructor function.
  17. * @example
  18. *
  19. * // Variadic Constructor function
  20. * function Salad() {
  21. * this.ingredients = arguments;
  22. * }
  23. *
  24. * Salad.prototype.recipe = function() {
  25. * const instructions = R.map(ingredient => 'Add a dollop of ' + ingredient, this.ingredients);
  26. * return R.join('\n', instructions);
  27. * };
  28. *
  29. * const ThreeLayerSalad = R.constructN(3, Salad);
  30. *
  31. * // Notice we no longer need the 'new' keyword, and the constructor is curried for 3 arguments.
  32. * const salad = ThreeLayerSalad('Mayonnaise')('Potato Chips')('Ketchup');
  33. *
  34. * console.log(salad.recipe());
  35. * // Add a dollop of Mayonnaise
  36. * // Add a dollop of Potato Chips
  37. * // Add a dollop of Ketchup
  38. */
  39. var constructN =
  40. /*#__PURE__*/
  41. _curry2(function constructN(n, Fn) {
  42. if (n > 10) {
  43. throw new Error('Constructor with greater than ten arguments');
  44. }
  45. if (n === 0) {
  46. return function () {
  47. return new Fn();
  48. };
  49. }
  50. return curry(nAry(n, function ($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {
  51. switch (n) {
  52. case 1:
  53. return new Fn($0);
  54. case 2:
  55. return new Fn($0, $1);
  56. case 3:
  57. return new Fn($0, $1, $2);
  58. case 4:
  59. return new Fn($0, $1, $2, $3);
  60. case 5:
  61. return new Fn($0, $1, $2, $3, $4);
  62. case 6:
  63. return new Fn($0, $1, $2, $3, $4, $5);
  64. case 7:
  65. return new Fn($0, $1, $2, $3, $4, $5, $6);
  66. case 8:
  67. return new Fn($0, $1, $2, $3, $4, $5, $6, $7);
  68. case 9:
  69. return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8);
  70. case 10:
  71. return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9);
  72. }
  73. }));
  74. });
  75. export default constructN;