Skip to content

Instantly share code, notes, and snippets.

@joshburgess
Last active May 10, 2018 16:47
Show Gist options
  • Save joshburgess/7fb299351d21c54236de1ae38a114e5d to your computer and use it in GitHub Desktop.
Save joshburgess/7fb299351d21c54236de1ae38a114e5d to your computer and use it in GitHub Desktop.
A utility to match on expressions built by dynamically building a switch statement and evaluating it with eval
// try in ramda's repl: https://goo.gl/VsRkoY
const expMatch = cases => fallback => matchVal => {
const sanitize = maybeString =>
typeof maybeString === 'string' || maybeString instanceof String
? `'${maybeString}'`
: maybeString
// dynamically build a switch statement to be eval'd
const switchStart = `switch (true) {\n`
const switchEnd = `default: return ${sanitize(fallback)}\n}`
const toCaseString = ([exp, val]) => `case (${exp}): return ${sanitize(val)}\n`
const switchCases = cases(matchVal).map(toCaseString).join('')
const switchString = `${switchStart} ${switchCases} ${switchEnd}`
const iife = `(() => { ${switchString} })()`
return eval(iife)
}
// use a function to delay passing in the value we want to match on
// we could skip this step, but doing this makes it more reusable,
// because it allows partially applying arguments
const caseMap = val => [
[val <= 0, 'Solid'],
[val > 0 && val < 100, 'Liquid'],
]
const defaultVal = 'Gas'
expMatch(caseMap)(defaultVal)(38) // "Liquid"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment