Created
December 15, 2019 07:47
-
-
Save jgusta/f230578f196794c2fcbc072572cfd511 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
source: https://codeburst.io/alternative-to-javascripts-switch-statement-with-a-functional-twist-3f572787ba1c | |
the match() function is an alternative to a switch statement. | |
Benefits are: | |
The chain is an expression, unlike a switch statement. | |
Each case has its own scope. | |
The default case (.otherwise()) is mandatory. | |
result = match(2) | |
.on(x => x === 1, x => `${x} is one`) | |
.on(x => x === 2, x => `${x} is two`) | |
.on(x => x === 2, x => { | |
console.log(`this shouldn't run`); | |
return `${x} is two but we should never get here`; | |
}) | |
.on(x => x === 3,x => `${x} is three`) | |
.otherwise(x => `${x} is something else`); | |
result is "2 is two" AND console.log() was never called | |
alternatively pass a value instead of a function into the first | |
parameter of on() | |
result = match(2) | |
.on(2, x => `${x} is two`) | |
.otherwise(x => `${x} is something else`); | |
*/ | |
// source: https://stackoverflow.com/a/7356528 | |
const isFunction = function isFunction(check) { | |
return check && {}.toString.call(check) === "[object Function]"; | |
}; | |
const matched = x => ({ | |
on: () => matched(x), | |
otherwise: () => x | |
}); | |
// modified to optionally accept a single value instead of a function for first parameter | |
const match = x => ({ | |
on: (pred, fn) => | |
(isFunction(pred) ? pred(x) : pred === x) ? matched(fn(x)) : match(x), | |
otherwise: fn => fn(x) | |
}); | |
// optionally use this as a module, so in another file you can do | |
// const match = require(./match.js); | |
module.exports = match; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment