DEV Community

Discussion on: Why I prefer objects over switch statements

Collapse
 
qm3ster profile image
Mihail Malo

My favorite is that if the object is in the outer scope, you can statically link to a value instead of having a function call with a hardcoded string argument.
In many cases this enables making definitions not recursive, like the example in my post:

I just wish other people were more accepting of this approach.
That's not always the case :v

I am glad you mentioned the pattern matching proposal, in my opinion the closest implementation of it in current JS is actually the early return pattern:

const aMatchingFunction = arg => {
  if (typeAssertion(arg)) throw new Error(`Bad types`)

  if (matchPredicate1(arg) return matchBody1(arg)

  if (matchPredicate2(arg) return matchBody2(arg)

  const {param} = arg
  if (param && matchPredicate3(param)) return matchBody3(param)

  throw new Error(`No match, got ${arg}`)
}

It looks imperative at a glance, but with just a little discipline it serves the role very well.