Last active
March 18, 2019 04:37
-
-
Save simonwjackson/38bff1bf768e47046ddf6d13562dc004 to your computer and use it in GitHub Desktop.
Recipe scaler
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
const R = require('ramda') | |
const recipie = { | |
ingredients: [{ | |
name: 'butter', | |
weight: 100 | |
}, { | |
name: 'salt', | |
weight: 25 | |
}] | |
} | |
const largest = R.reduce(R.max, -Infinity) | |
const largestBy = key => R.compose( | |
largest, | |
R.chain(R.props([key])) | |
) | |
const toRatio = R.curry((list, largest) => | |
R.map(row => | |
R.assoc('ratio', R.divide(row.weight, largest), row), | |
list | |
)) | |
const ratioFrom = key => R.ap( | |
toRatio, | |
largestBy(key) | |
) | |
const scaleBy = name => weight => R.ap( | |
list => factor => R.map(R.evolve({ | |
weight: R.multiply(factor) | |
}), list), | |
R.compose( | |
R.divide(weight), | |
R.prop('weight'), | |
R.find(R.propEq(name)) | |
) | |
) | |
R.compose( | |
R.over(R.lensProp('ingredients'), scaleBy('butter')(15)), | |
R.over(R.lensProp('ingredients'), ratioFrom('weight')), | |
)(recipie) | |
// Object | |
// ingredients: Array (2 items) | |
// 0: Object {name: "butter", ratio: 1, weight: 15} | |
// 1: Object {name: "salt", ratio: 0.25, weight: 3.75} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment