Created
April 22, 2020 16:34
-
-
Save lund0n/ba432bbd9f609dfee5de6f1f373bfc27 to your computer and use it in GitHub Desktop.
Ramda Example
This file contains 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
// from Egghead video: https://egghead.io/lessons/javascript-handle-branching-logic-with-ramda-s-conditional-functions | |
import * as R from 'ramda' | |
const products = [ | |
{ name: 'Jeans', price: 80, category: 'clothes' }, | |
{ name: 'Cards', price: 5, category: 'games' }, | |
{ name: 'iPhone', price: 649, category: 'electronics' }, | |
{ name: 'Freakonomics', price: 30, category: 'books' }, | |
] | |
const pLens = R.lensProp('price') | |
const applyDiscount = R.curry((perc, amt) => amt - amt * (perc / 100)) | |
// Original (from video) | |
const adjustPrice = R.cond([ | |
[R.propEq('category', 'clothes'), R.over(pLens, applyDiscount(50))], | |
[R.propEq('category', 'electronics'), R.over(pLens, applyDiscount(10))], | |
[R.propEq('category', 'books'), R.over(pLens, applyDiscount(100))], | |
[R.T, R.identity], | |
]) | |
// Refactor (using a DISCOUNTS object) | |
const DISCOUNTS = { | |
clothes: 50, | |
electronics: 10, | |
books: 100, | |
} | |
const adjustPrice2 = R.compose( | |
R.cond, | |
R.append([R.T, R.identity]), | |
R.map(([category, discount]) => [ | |
R.propEq('category', category), | |
R.over(pLens, applyDiscount(discount)), | |
]), | |
R.toPairs | |
)(DISCOUNTS) | |
const result = R.map(adjustPrice, products) | |
const result2 = R.map(adjustPrice2, products) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment