Skip to content

Instantly share code, notes, and snippets.

View frivolta's full-sized avatar

Filippo Rivolta frivolta

View GitHub Profile
const multiply20 = (price) => price * 20;
const divide100 = (price) => price / 100;
const normalizePrice = (price) => price.toFixed(2);
// result = a(b(c(x)))
const discount = normalizePrice(divide100(multiply20(200))); // 40.00
const compose = (a, b, c) => (x) => a(b(c(x)));
const discount = compose(normalizePrice, divide100, multiply20);
discount(200.0); //40.00
const compose =
(...fns) =>
(x) =>
fns.reduceRight((res, fn) => fn(res), x);
const addPrefix = (price) => "$" + String(price); //$ 40.00
const discountWithPrefix = compose(
addPrefix,
normalizePrice,
divide100,
multiply20
);
discountWithPrefix(200.0); // '$40.00'
const pipe =
(...fns) =>
(x) =>
fns.reduce((res, fn) => fn(res), x);
const multiply20 = (price) => price * 20;
const divide100 = (price) => price / 100;
const normalizePrice = (price) => price.toFixed(2);
const addPrefix = (price) => "$" + String(price);
const pipe =
(...fns) =>
(x) =>
fns.reduce((res, fn) => fn(res), x);
const compose =
@frivolta
frivolta / hof.js
Created May 27, 2022 15:28
Write better React, compose multiple functional HoCs, Higher-Order Components - Array.prototype.map
// Result is [2,3,4]
[1,2,3].map((number)=>number+1)
// Note that you can extract the callback function and pass it to the map function:
function addOne(arg){
return arg+1
}
[1,2,3].map((number)=>addOne(number))
// or
@frivolta
frivolta / custom-hof.js
Created May 27, 2022 15:31
Write better React, compose multiple functional HoCs, Higher-Order Components - Custom Higher Order Function
// We first define the function we will be using as an argument
const addOne = (arg)=>arg+1
// We than define our hof
const higherOrderFunction = (fn, arg) => fn(arg)*2
// The result will be 12
higherOrderFunction(addOne, 5)