Skip to content

Instantly share code, notes, and snippets.

@wuct
Last active March 7, 2016 16:05
Show Gist options
  • Select an option

  • Save wuct/19e85b98cc7fe12a7b0a to your computer and use it in GitHub Desktop.

Select an option

Save wuct/19e85b98cc7fe12a7b0a to your computer and use it in GitHub Desktop.
A functional implementation of switch
// 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'
)
@wuct
Copy link
Copy Markdown
Author

wuct commented Mar 6, 2016

We can not use switch, case and default, because they are already used in JavaScript. Need to find other names.

@wuct
Copy link
Copy Markdown
Author

wuct commented Mar 6, 2016

Just come up with some candidates of names:

  • switch can be condition;
  • case can be when or unless;
  • default can be otherwise.

Result:

const isFruitOrVegetable = condition(
  when('apple', 'isFruit'),
  when('orange', 'isFruit'),
  when('eggplant', 'isVegetable'),
  otherwise('isFruit')
);

@wuct
Copy link
Copy Markdown
Author

wuct commented Mar 7, 2016

@wuct
Copy link
Copy Markdown
Author

wuct commented Mar 7, 2016

@wuct
Copy link
Copy Markdown
Author

wuct commented Mar 7, 2016

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';
}

@jackypan1989
Copy link
Copy Markdown

nice (thumb

@wuct
Copy link
Copy Markdown
Author

wuct commented Mar 7, 2016

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