JavaScript does not have native support for match
statement introduced in other languages
such as Rust, PHP and most recently Python.
The main advantage of match
is that it provides a more concise and readable way to
handle multiple conditions compared to switch
statement or if-elseif-else
chain.
This gist demonstrates a possible implementation of such functionality in JavaScript.
let value = match(expr,
[CASE_1, RETURN_X],
[CASE_2, RETURN_Y],
...
[CASE_N, RETURN_N],
);
function match(expr, ...cases)
{
for (const [k, v] of cases) {
if (expr === k) return v;
}
}
Note that return is not limited to a pre-defined value,
an extended implementation can include
expressions which are executed just-in-time.
let value = match(expr,
[CASE_1, function.bind(thisArg, param)],
[CASE_1, function.bind(thisArg, param)],
...
[CASE_N, RETURN_N],
);
function match(expr, ...cases)
{
for (const [k, v] of cases)
{
if (expr !== k) {
continue;
}
if (v instanceof Function) {
return v(); // JIT execution
}
return v;
}
}
// returns two
let value = match(2,
[1, 'one'],
[2, 'two'],
[3, 'err'],
);
// and if we were to write the same code
// using the good old switch statement:
let value = null;
switch (2)
{
case 1:
value = 'one';
break;
case 2:
value = 'two';
break;
case 3:
value = 'err';
break;
}