Skip to content

Instantly share code, notes, and snippets.

@nebomilic
Created December 31, 2019 10:51
Show Gist options
  • Save nebomilic/38f8290128ab0b37695ac0ae9900bb0a to your computer and use it in GitHub Desktop.
Save nebomilic/38f8290128ab0b37695ac0ae9900bb0a to your computer and use it in GitHub Desktop.
Pattern matching pattern in javascript
// pattern matching is a nice mechanism supported by most functional languages (eg see scala examples: https://docs.scala-lang.org/tour/pattern-matching.html)
// here are some ways to use javascript switch and if statement for pattern matching
// we are using IIFE pattern to immediately invoke switch (or if) statement
const value1 = 1;
// version using switch case
const value2 = (_ => {
switch (true) {
case value1 === 1: return 'first case';
case value1 === 2: return 'second case';
case value1 === 3: return 'third case';
default: return 'no match found';
}
})()
// version using if else
const value3 = (_ => {
if ( value1 === 1) return 'first case';
if ( value1 === 2) return 'second case';
if ( value1 === 3) return 'third case!';
return 'no match found';
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment