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

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more