Introduction
In this lab, we will be exploring the concept of currying in JavaScript. Currying is a technique that allows us to transform a function that takes multiple arguments into a sequence of functions that each take a single argument. Through this lab, you will gain a deeper understanding of how currying works and how it can be applied in your JavaScript code.
This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.
Currying a Function
To curry a function, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use recursion.
- Check if the number of provided arguments (
args) is sufficient. - If yes, call the passed function
fn. - If not, use
Function.prototype.bind()to return a curried functionfnthat expects the rest of the arguments. - If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g.
Math.min()), you can optionally pass the number of arguments to the second parameterarity. - Use the following code:
const curry = (fn, arity = fn.length, ...args) =>
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
Here are some examples:
curry(Math.pow)(2)(10); // 1024
curry(Math.min, 3)(10)(50)(2); // 2
Summary
Congratulations! You have completed the Curry Function lab. You can practice more labs in LabEx to improve your skills.