etcbad.blogg.se

Javascript pattern matching
Javascript pattern matching











javascript pattern matching

What are we doing with the switch expression and the cases exactly? We're strictly comparing ( =) two values and seeing if they come out true or false. However, this limits how useful our switch can be because we can only operate on a single value in the expression. Variants type schoolPerson = Teacher | Director | Student (string ) let greeting = person => // Pattern matching switch switch (person ) default : return stateĪs we make calls to reducer, our switch tries to match the action.type to the case with the same string. On their home page, they share this example:

javascript pattern matching

With ReasonML's switch, when we pass in a value, we can respond differently based on the variant of that value. A variant, is one type in a set of types. In ReasonML, a strongly typed functional language, you have variants. I first encountered "pattern matching" when I started to learn ReasonML a few years ago. If you're not familiar with how they work in JavaScript, I recommend reading the MDN docs on switch. It's not quite the real thing, but it does a pretty good job of coming close to it and is plenty useful.īefore you go further, you should understand switch statements pretty well. I call what I'm about to show you "a poor person's pattern matching" or "makeshift pattern matching". It shouldn't be called that, but I'll take it as a compliment. In fact, I use this pattern so often that my manager at work started to call it the "Kyle pattern". I've made several tweets about it throughout the years and it's high time that I finally write a blog post that I can use as a reference. Today, I want to share with you a coding pattern I frequently use when writing conditional JavaScript.













Javascript pattern matching