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' | |
) |
We can not use switch
, case
and default
, because they are already used in JavaScript. Need to find other names.
Just come up with some candidates of names:
switch
can becondition
;case
can bewhen
orunless
;default
can beotherwise
.
Result:
const isFruitOrVegetable = condition(
when('apple', 'isFruit'),
when('orange', 'isFruit'),
when('eggplant', 'isVegetable'),
otherwise('isFruit')
);
We can achieve 'fall through' cleaner by extracting out common code.
const fruit = str => when(str, 'isFruit')
const vegetable = str => when(str, 'isVegetable')
const isFruitOrVegetable = condition(
fruit('apple'),
fruit('orange'),
vegetable('eggplant'),
otherwise('isFruit')
);
To compare with the original switch statement
switch(str) {
case 'eggplant':
return 'isVegetable';
case 'apple':
case 'orange':
default:
return 'isFruit';
}
nice (thumb
I have opened a repo for this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Other implements:
https://www.npmjs.com/package/semantic-switch
https://www.npmjs.com/package/better-switch
https://www.npmjs.com/package/switch-fn