Published
Edited
Dec 21, 2018
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// Say we're buying a $10 item online.
ITEM_PRICE = 10
Insert cell
// Non functional style. We included tax + shipping.
{
const calculateTotal = (baseCost) => (1.06 * baseCost) + 10;
return calculateTotal(ITEM_PRICE)
}
Insert cell
Insert cell
applyTax = (baseCost) => baseCost * 1.06
Insert cell
applyShipping = (baseCost) => baseCost + 10
Insert cell
// Naive composition
applyShipping(applyTax(ITEM_PRICE))
Insert cell
Insert cell
R = require('ramda@0.25.0/dist/ramda.min.js')
// Don't use latest ramda due to an importing issue
// see https://talk.observablehq.com/t/imports-create-circular-definition/870/3
Insert cell
calculateTotalComposed = R.compose(applyShipping,
applyTax) // applied RIGHT to LEFT (from inside, out)
Insert cell
calculateTotalComposed(ITEM_PRICE)
Insert cell
Insert cell
calculateTotalPipe = R.pipe(applyTax, applyShipping)
Insert cell
calculateTotalPipe(ITEM_PRICE)
Insert cell
Insert cell
Insert cell
applySaleDiscount = (baseCost) => (0.9 * baseCost) // 10% off!
Insert cell
calculateTotalPipeSale = R.pipe(applySaleDiscount,
applyTax,
applyShipping)
Insert cell
calculateTotalPipeSale(ITEM_PRICE)
Insert cell
// compare this to the readability of the first cell...
{
const calculateTotalSale = (baseCost) => (1.06 * baseCost * .9) + 10;
return calculateTotalSale(ITEM_PRICE)
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more