Build a table of business rules
Replace a ladder of if statements with a router of rules, general and special, each added on its own.
Use this when a rule has sub-cases and sub-sub-cases, such as a tax rate that differs by country, then by state, then by city. Add a pattern for each case, from the general to the special, and let the router choose. Here each pattern holds a function that gives the rate of a sale:
const patrun = require('patrun')
const rate = (value) => () => value
const salestax = patrun()
.add({}, rate(0))
.add({ country: 'IE' }, rate(0.25))
.add({ country: 'IE', type: 'food' }, rate(0.048))
.add({ country: 'IE', type: 'reduced' }, rate(0.135))
.add({ country: 'US' }, rate(0))
.add({ country: 'US', state: 'AL' }, rate(0.04))
.add({ country: 'US', state: 'AL', city: 'Montgomery' }, rate(0.1))
.add({ country: 'US', state: 'NY' }, rate(0.07))
.add({ country: 'US', state: 'NY', type: 'reduced' }, (net) =>
net < 110 ? 0 : salestax.find({ country: 'US', state: 'NY' })(net),
)
salestax.find({ country: 'IE', type: 'food' })(99) // → 0.048
salestax.find({ country: 'US', state: 'AL', city: 'Montgomery' })(99) // → 0.1
salestax.find({ country: 'US', state: 'NY', type: 'reduced' })(99) // → 0
salestax.find({ country: 'US', state: 'NY', type: 'reduced' })(120) // → 0.07
salestax.find({ country: 'FR' })(99) // → 0
The last rule shows why the data is a function: a rate in New York that depends on the size of the sale is code, and it can fall back on the state's own rule.
What to watch for #
Each rule is added and removed on its own, so a new case is a new line, not a change to a branch of an if ladder. When two rules match a sale with as many properties, the first property where they differ decides between them, with keys in the key order: name the key that matters most with the order option, as Choose which keys come first shows. In Go, where a pattern's data is a string, store a key into your own table of functions.