Currying Function in JavaScript
Level 5422 keystrokes
This implements a curry function that transforms multi-argument functions.
JavaScript code
// Curry: transforms f(a, b, c) into f(a)(b)(c) or any combination1function curry(fn) { // Return a function that collects arguments2 return function curried(...args) { // If we have enough arguments, call the original function // fn.length is the number of parameters fn expects3 if (args.length >= fn.length) {4 return fn.apply(this, args);5 } // Not enough arguments - return function to collect more6 return function(...moreArgs) { // Combine all arguments and recurse7 return curried.apply(this, args.concat(moreArgs));8 };9 };10}11 // Original function takes 3 arguments12function add(a, b, c) {13 return a + b + c;14}15 // Create curried version16const curriedAdd = curry(add);17 // All these produce 6:18console.log(curriedAdd(1, 2, 3));19console.log(curriedAdd(1)(2)(3));20console.log(curriedAdd(1, 2)(3));21console.log(curriedAdd(1)(2, 3));Output
6 6 6 6
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 21)× 21.× 15;× 10,× 8{× 5}× 5+× 2=× 2>× 1