|
| 1 | +```js |
| 2 | +/** |
| 3 | + * Transforms a function into its curried form. |
| 4 | + * |
| 5 | + * @param {Function} func - The function to curry. |
| 6 | + * @returns {Function} - The curried function. |
| 7 | + */ |
| 8 | +export default function curry(func) { |
| 9 | + if (typeof func !== 'function') { |
| 10 | + throw new TypeError('Expected a function'); |
| 11 | + } |
| 12 | + |
| 13 | + // Return a function that collects arguments until the required number is reached |
| 14 | + function curried(...args) { |
| 15 | + // Check if we have the correct number of arguments |
| 16 | + if (args.length >= func.length) { |
| 17 | + // If we have enough arguments, call the original function |
| 18 | + return func(...args); |
| 19 | + } |
| 20 | + |
| 21 | + // If not, return a function to collect more arguments |
| 22 | + return function (...nextArgs) { |
| 23 | + return curried(...args, ...nextArgs); // Combine all arguments and call curried again |
| 24 | + }; |
| 25 | + } |
| 26 | + |
| 27 | + return curried; |
| 28 | +} |
| 29 | +``` |
| 30 | + |
| 31 | +### Explanation |
| 32 | +#### Validate Input: |
| 33 | + |
| 34 | +* Ensure `func` is a valid function; otherwise, throw a TypeError. |
| 35 | +#### Main Logic: |
| 36 | + |
| 37 | +* Use a `recursive closure` to collect arguments: |
| 38 | +* If the number of collected arguments (args.length) is greater than or equal to the number of arguments that the original function expects (func.length), directly invoke the original function with those arguments. |
| 39 | +* If not, return a new function that continues collecting arguments until enough have been supplied. This recursively calls the curried function with the combined arguments. |
| 40 | +#### Handling Multiple Calls: |
| 41 | + |
| 42 | +* Use the `rest operator (...args)` to collect the current arguments and spread them when recursively calling. |
| 43 | +#### Base Case: |
| 44 | + |
| 45 | +* When the total number of arguments collected is equal to or greater than the original function's arity (func.length), invoke the original function with all the supplied arguments. |
0 commit comments