I have a question similar to this one, except with Javascript instead of C#.
Basically, I want to be able to do pattern matching on an expression instead of using a long list of if statements, like this:
var person.annoyingAction = match([person.gender, person.ageGroup],
[male, child], breakingStuff,
[male, teenager], drivingRecklessly,
[male, adult], beingLazyAfterComingHomeFromWork
[female, child], screechingInAnUnbelievablyHighPitchedVoice,
[female, teenager], knowingEverything,
[female, adult], askingPeopleIfTheyThinkIAmTooFat
[_, baby], cryingEveryTwoHoursAtNight,
[_,_], beingHuman);
Does anybody know how to implement something that would do something like this in Javascript?
I don’t know of an existing, clean, solution, but here is a simple implementation that matches what your example:
Example use:
In JavaScript you can’t compare arrays directly (
[1, 2] != [1, 2]) so you need to compare the elements individually.