Created
December 31, 2019 10:51
-
-
Save nebomilic/38f8290128ab0b37695ac0ae9900bb0a to your computer and use it in GitHub Desktop.
Pattern matching pattern in javascript
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
// 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