Summary - Functional programming
Build a price-calculation chain using compose and curry.
Summary - Functional programming
In this group you learned four core ideas. Pure functions have no side effects and return the same output for the same input. Immutability copies data instead of changing it. Composition combines small functions. Currying binds arguments one at a time.
Together, these four produce code that is easy to read, test, and reuse. Now we will combine all of them in a price-calculation chain.
Exercise Build a price-calculation chain
Build a price-calculation chain. First write a pure arrow function named addTax: price => price * 1.2. Then define a compose helper: (f, g) => x => f(g(x)). Write a double function: x => x * 2. Then call const total = compose(addTax, double); and console.log(total(100));.
Show example solution
const addTax = price => price * 1.2;
const compose = (f, g) => x => f(g(x));
const double = x => x * 2;
const total = compose(addTax, double);
console.log(total(100));
Test yourself
-
Match the functional concepts
- pure function
- no side effects
- immutability
- copy, don't mutate
- compose
- f(g(x))
- curry
- arguments one by one
-
Which one follows the functional style?
- prices.map(p => p * 1.2)
- user.age = 30;
- prices.push(100);
- for (let i = 0; i < arr.length; i++) { arr[i]++; }
Show answer
prices.map(p => p * 1.2) — Correct! map returns a new array and does not mutate the original; that is functional style.
-
Complete the final call of the chain
const addTax = price => price * 1.2; const result = addTax(____);Show answer
const addTax = price => price * 1.2; const result = addTax(100);