Matching Expression Patterns

I have a question similar to this , with the exception of Javascript instead of C #.

Basically, I want to be able to match patterns in an expression instead of using a long list of operators if, for example:

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 anyone know how to implement something like this in Javascript?

+3
source share
1 answer

I don't know about the existing, clean, solution, but here is a simple implementation that matches 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];
    }
  }
}

Usage example:

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 cannot compare arrays directly ( [1, 2] != [1, 2]), so you need to compare elements separately.

+1
source

All Articles