tc39 / proposal-pattern-matching

Pattern matching syntax for ECMAScript
https://tc39.es/proposal-pattern-matching/
MIT License
5.5k stars 89 forks source link

https://dart.dev/language/patterns #299

Closed HudsonAfonso closed 7 months ago

HudsonAfonso commented 1 year ago

https://dart.dev/language/patterns

tabatkins commented 1 year ago

Ooooh, this has a really nice example of how patterns make validating JSON super compact and readable. Gonna translate it back to plain JS and store it here, so I can grab it later when we merge the new-README branch.


Destructuring, no checks:

var json = {
  'user': ['Lily', 13]
};
var {user: [name, age]} = json;

Destructuring with checks that everything is correct and of the expected shape:

if ( json.user !== undefined ) {
  var user = json.user;
  if (Array.isArray(user) &&
      user.length == 2 &&
      typeof user[0] == "string" &&
      typeof user[1] == "number") {
    var name = user[0];
    var age = user[1];
    print(`User ${name} is ${age} years old.`);
  }
}

Same checks, but in pattern-matching:

if( json is {user: [String and let name, Number and let age]} ) {
  print(`User ${name} is ${age} years old.`);
}