# Practical introduction to Functional Programming with JS

legendtariq
1,074 views

## Currying

Currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument.

This becomes very easy using lambda functions and closures. So let's dive straight into code:

Get the even numbers in an array
1
2
3
4
5
6
7
8
9
10
11
12
13
// standard way
return x + y + z;
}
// curried style
const add2 = x => // if you have only one argument in the lambda function you can omit the parenthesis
y =>
z =>
x + y + z;
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

So why is this useful? Because we are now able to pass the arguments at different points in time, this means that we can use currying to "construct" a function.

E.g.

Generic filter callback to check any property of an object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const checkProperty = propertyName =>
expectedValue =>
object =>
object[propertyName] === expectedValue;
const candies = [
{"soft":true, "flavour":"strawberry"},
{"soft":false, "flavour":"strawberry"},
{"soft":false, "flavour":"cherry"},
{"soft":true, "flavour":"orange"},
{"soft":false, "flavour":"lemon"},
];
const softCandies = candies.filter( checkProperty("soft")(true) ); // checkProperty("soft")(true) returns a function that accepts an object, exactly what we need
console.log(softCandies);
const strawberryCandies = candies.filter( checkProperty("flavour")("strawberry") );
console.log(strawberryCandies);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

And now time to get your hands dirty: remember the applyCoupon function we wrote in the previous chapter? It was very specific, now we want to create a curryable function that takes as arguments (in this order) category, discount between 0 and 1 (0.8 = 80% discount) and then an item and returns the item with the correct price.
Remember to apply the discount only to the right items!

Implement applyCoupon as a curriable function
1
2
3
const applyCoupon = // this should be a curried function
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn.