January 4, 2019

For the past months I’ve been exploring with a pattern for JavaScript projects that I call Map-To. It’s a simple way to avoid conditionals; à la pattern matching.

Back Story

I was exposed to a similar idea when first writing an application using Redux to handle state management.

Redux exposes a [connect()](<https://react-redux.js.org/api/connect>) function that takes in two other functions as arguments: mapStateToProps() and mapDispatchToProps(). This enables custom mapping functions to be implemented so you can have control of how data and actions flow through your application.

Reading a piece of code that implements connect() one can easily understand its intent, just by simply relying on this naming convention. This got me thinking if it wouldn’t be possible to apply the same idea elsewhere.

The pattern

The idea is to use a variable that will hold all possible variations for a specific value.

Say you want to match a given route value to a specific color. If no valid value is provided, the program should default to fuchsia.

By using conditionals, you can implement it like this:

// Using "if"

let color /* = 'gray' */

if (route === Routes.RED) {
  color = 'red'
} else if (route === Routes.GREEN) {
  color = 'green'
} else if (route === Routes.BLUE) {
  color = 'blue'
} else {
  color = 'fuchsia'
}

// Using "switch"

let color /* = 'gray' */

switch (route) {
  case Routes.RED:
    color = 'red'
    break

  case Routes.GREEN:
    color = 'green'
    break

  case Routes.BLUE:
    color = 'blue'
    break

  default:
    color = 'fuchsia'
}

With Map-To, the implementation would look like this:

const mapRouteToColor = {
  [Routes.RED]: 'red',
  [Routes.GREEN]: 'green',
  [Routes.BLUE]: 'blue'
}

const color = mapRouteToColor[route] ?? 'fuchsia'

Keep in mind that object keys can be anything, so you don’t necessarily have to stick to string values: