Reputation: 143037
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?
Upvotes: 3
Views: 172
Reputation: 129756
I don't know of an existing, clean, solution, but here is a simple implementation that matches what your example:
var match = function(target) {
for (i = 1; i < arguments.length; i += 2) {
if (target[0] == arguments[i][0] && target[1] == arguments[i][1]) {
return arguments[i + 1];
}
}
}
Example use:
var result = match(["Yellow", "Food"],
["Red", "Food"], "Apple",
["Green", "Plant"], "Grass",
["Yellow", "Thing"], "Schoolbus",
["Yellow", "Food"], "Banana",
["Yellow", "Foot"], "Bad"
)
alert(result) # displays "Banana"
In JavaScript you can't compare arrays directly ([1, 2] != [1, 2]
) so you need to compare the elements individually.
Upvotes: 1