Flexible switch statements using arrow functions

Hi everyone,
Switch statements in JavaScript are currently limited in functionality. We don't often see them in code (except in Redux applications).
They are just good for equality compare.
I'm just suggesting an add-on to their functionality.
syntax

switch((x, y) => x < y) {
    case 1, 2 : /*do something*/;
    break;
    case 10, 5 : /*do something*/;
    break;
    default: console.log("Something's not right");
}

class Element {}
switch(x => Element instanceof x) {
   case React.Component: /*do something*/;
   break;
   case customElements: /*do something*/;
   break;
   case HTMLElement: /*do something*/;
   break;
   case Error: /*do something*/;
   default: console.log("Yay, whatever! ");
}
//etc, etc...

This seems like the match statement in Rust right??
However there should be some restrictions upon the function passed to the switch.
It must be an arrow function with implicit return
i.e,

//The following invalid switch statements :( will result in an error
switch(x => { return !!x }) {
/*
     switch body
*/
}

switch(function(x) { return !!x }) {
/*
     switch body
*/
}

Alright, what does everyone think about this??
What are the pros and cons??
Please mention!

For your use case, an if/else chain seems more appropriate, as the repeated tests would be what your proposed switch statement desugars to anyway. It's also shorter and doesn't need break statements to avoid fallthrough:

if (1 < 2) { /* do something */; }
else if (10 < 5) { /* do something */; }
else { console.log("Something's not right"); }
if (Element instanceof React.Component) { /*do something*/; }
else if (Element instanceof customElements) { /*do something*/; }
else if (Element instanceof HTMLElement) { /*do something*/; }
else if (Element instanceof Error) { /*do something*/; }
else { console.log("Yay, whatever! "); }

The power of switch is in optimisations that are only possible with equality comparisons.

For that, see the pattern matching proposal.

1 Like