Last active
March 7, 2016 16:05
-
-
Save wuct/19e85b98cc7fe12a7b0a to your computer and use it in GitHub Desktop.
A functional implementation of switch
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
// simple example | |
const isFruitOrVegetable = switch( | |
case('apple', 'isFruit'), | |
case('orange', 'isFruit'), | |
case('eggplant', 'isVegetable'), | |
default('isFruit') | |
); | |
isFruitOrVegetable('apple') // isFruit | |
// We can also pass regular expressions or functions to case. | |
// For example: | |
case( | |
/apple/, | |
() => 'isFruit' | |
) | |
case( | |
str => str.includes('eggplant'), | |
() => 'isVegetable' | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can achieve 'fall through' cleaner by extracting out common code.
To compare with the original switch statement