Last active
December 2, 2021 07:24
-
-
Save iexa/f29fa62abcbb825a06049bd8f39c9d5c to your computer and use it in GitHub Desktop.
functional example cart with reduce in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user = { | |
name: 'Joe', | |
active: true, | |
purchases: [], | |
cart: [] | |
} | |
const compose = (f, g) => { return (...args) => f(g(...args)) } // in reduce new acc/f will be a fn | |
// all functions are coiled up from last to first - | |
// last one gets n-ary arguments, the rest passes only 1 out -> 1 in | |
function purchaseItem(...fns) { return fns.reduce(compose) } | |
purchaseItem( | |
emptyCart, | |
buyItem, | |
applyTaxToItems, | |
addItemToCart | |
)(user, {name: 'macbook pro m1 64g', price: 5000}) | |
function addItemToCart(user, item) { | |
console.log('additemtocart') | |
const cart2 = user.cart.concat(item) | |
return Object.assign({}, user, {cart: cart2}) | |
} | |
function applyTaxToItems(user) { | |
console.log('applytax') | |
const {cart} = user | |
const up = cart.map( i => ({name: i.name, price: i.price*1.3}) ) | |
return Object.assign({}, user, {cart: up}) | |
} | |
function buyItem(user) { | |
console.log('buyitem') | |
return Object.assign({}, user, {purchases: user.cart}) | |
} | |
function emptyCart(user) { | |
console.log('emptycart') | |
return Object.assign({}, user, {cart: []}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment