Skip to content

Instantly share code, notes, and snippets.

@domtronn
Created February 13, 2020 11:24
Show Gist options
  • Save domtronn/9f51d8732e01d6b85c9494715aeb383c to your computer and use it in GitHub Desktop.
Save domtronn/9f51d8732e01d6b85c9494715aeb383c to your computer and use it in GitHub Desktop.
A functional cond/case switch statement in js
/**
* @typedef {Function} CaseFunction
* @param {...*} [args] - List of args provided to anonymous function
*/
/**
* @typedef {Function} SwitchFunction
* @param {string} [c='default'] - case string to match
* @param {...*} [args] - args to pass to matched SwitchFunction
* @returns {*} - Result of matching case in SwitchMap either CaseFunction called with args, or value
*/
/**
* @typedef {Object<string, CaseFunction|*>} SwitchMap
*/
/**
* sw.js
*
* This function takes a SwitchMap and returns a SwitchFunction which
* can be called with a case property and extra args to match with
* function
*
* @example
* sw({
* foo: i => i + 2, // 5
* bar: 'baz', // bar
* default: null, // null
* })('foo', 3)
*
* @param {SwitchMap} cases - A map of string cases to value or CaseFunction call
* @returns {SwitchFunction}
*/
export default cases => (c, ...args) => {
const f = {}.hasOwnProperty.call(cases, c)
? cases[c]
: cases.default
return f instanceof Function ? f(...args) : f
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment