Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
Currying is a programming technique that converts a complex function, which takes multiple inputs, into a series of functions that only accept one input.
For example, here is a function that calculates the final price of a meal, including tax and tip.
This is where the arrow function syntax really shines.
const calculateTotal = (baseCost) => (tax) => (tip) => {
const total = baseCost * (1 + tax / 100) * (1 + tip / 100);
return total.toFixed(2); // Round to 2 decimal places for cents
};
const applyTax = calculateTotal(25); // 25 is the base price
const applyTip = applyTax(13); // 13% tax
const totalPrice = applyTip(15); // 15% tip
console.log(totalPrice); // -> 32.49toFixed() is a built-in number method. It rounds the number to the specified decimal places.
const calculateTotal = (baseCost) => (tax) => (tip) => {
const total = baseCost * (1 + tax / 100) * (1 + tip / 100);
return total.toFixed(2); // Round to 2 decimal places for cents
};
const applyTax = calculateTotal(25); // 25 is the base price
const applyTip = applyTax(13); // 13% tax
const totalPrice = applyTip(15); // 15% tip
console.log(totalPrice); // -> 32.49The function calculateTotal() takes three steps to execute.
First, const applyTax = calculateTotal(25) passes 25 to baseCost, creating the function applyTax():
const applyTax = (tax) => (tip) => {
const total = 25 * (1 + tax / 100) * (1 + tip / 100);
return total.toFixed(2); // Round to 2 decimal places for cents
};And const applyTip = applyTax(13) passes 13 to tax, creating the function applyTip():
const applyTip = (tip) => {
const total = 25 * (1 + 13 / 100) * (1 + tip / 100);
return total.toFixed(2); // Round to 2 decimal places for cents
};Lastly, const totalPrice = applyTip(15) finishes the function by passing 15 to the final argument tip.
Yes, right now, it looks like a silly way to write this program, and it has only made things more complex than necessary. You could just calculate everything together, so why split an easy task into multiple steps?
In a real-world scenario, it is possible that the required arguments aren't provided at the same time, and the curring technique would create functions that "remember" the previously provided arguments, making your functions more flexible under different use cases.
const calculateTotal = (baseCost) => (tax) => (tip) => { const total = baseCost * (1 + tax / 100) * (1 + tip / 100); return total.toFixed(2); // Round to 2 decimal places for cents }; const applyTax = calculateTotal(25); // 25 is the base price const applyTip = applyTax(13); // 13% tax const totalPrice = applyTip(15); // 15% tip console.log(totalPrice); // -> 32.49