Skip to content

Instantly share code, notes, and snippets.

@mrpotatoes
Last active May 26, 2022 14:26
Show Gist options
  • Save mrpotatoes/e66055884a48c6d7155722cc9bf68b9e to your computer and use it in GitHub Desktop.
Save mrpotatoes/e66055884a48c6d7155722cc9bf68b9e to your computer and use it in GitHub Desktop.
console.clear()
const R = require('ramda')
const cart = [
{ name: 'apples', price: 2.49 },
{ name: 'soap', price: 1.99 },
{ name: 'milk', price: 2.99 },
{ name: 'eggs', price: 3.99 },
{ name: 'carrots', price: 2.99 },
{ name: 'butter', price: 1.49 },
{ name: 'fish', price: 9 },
{ name: 'lettuce', price: 2.99 },
{ name: 'broccoli', price: 4.99 },
{ name: 'lemons', price: 3.49 }
]
const toUSD = (amount) => amount.toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
})
// Pure functional approach
const getTotalPrice_FP = (cart) => R.pipe( //https://ramdajs.com/docs/#pipe
R.pluck('price'), // https://ramdajs.com/docs/#pluck
R.reduce(R.add, 0), // https://ramdajs.com/docs/#reduce
toUSD,
)(cart)
// Idiomatic JS apprpach. Harder to read but still not too bad.
const getTotalPrice_IDOMATIC_JS = (cart) => toUSD(cart
.map(p => p.price)
.reduce((prev, curr) => prev + curr, 0))
// Imperative approach. Yuckkers harder.
const getTotalPrice_IMPL = (cart) => {
let price = 0
for (let i = 0; i < cart.length; i++) {
price += cart[i].price
}
return toUSD(price)
}
console.log(getTotalPrice_FP(cart))
console.log(getTotalPrice_IDOMATIC_JS(cart))
console.log(getTotalPrice_IMPL(cart))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment