Skip to content

Instantly share code, notes, and snippets.

@lettapp
Created May 8, 2024 08:58
Show Gist options
  • Save lettapp/eae3082acff00ab6318796076c0962ca to your computer and use it in GitHub Desktop.
Save lettapp/eae3082acff00ab6318796076c0962ca to your computer and use it in GitHub Desktop.
Implementing match statement in JavaScript

Implementing match statement in JavaScript

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.

Basic Syntax

let value = match(expr,
  [CASE_1, RETURN_X],
  [CASE_2, RETURN_Y],
  ...
  [CASE_N, RETURN_N],
);

Implementation

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.

Extended Syntax

let value = match(expr,
  [CASE_1, function.bind(thisArg, param)],
  [CASE_1, function.bind(thisArg, param)],
  ...
  [CASE_N, RETURN_N],
);

Implementation

function match(expr, ...cases)
{
  for (const [k, v] of cases)
  { 
    if (expr !== k) {
      continue;
    }
    
    if (v instanceof Function) {
      return v(); // JIT execution
    }
    
    return v;
  }
}

Example

// 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment