Live data from Hacker News

JavaScript Pattern Matching Proposal

github.com

21–30 of 254 posts

Re: JavaScript Pattern Matching Proposal

#22

Could someone please explain what this could be used for ?

Smooshes the evaluation of an object that can be many different shapes into an easy to understand operation. I think the HTTP response is a great example. It can have many status codes which can determine how you want to proceed with that response. If you've worked with handling HTTP responses, you've most likely implemented some version of a 'match' operation before.

> Smooshes the evaluation

I see what you did there...

Re: JavaScript Pattern Matching Proposal

#24
Javascript is such a mess, this proposal looks really bad, and the guys discussing it are saying things like: "we should make sure that this doesn't look like anything else, so that people who learn the language don't confuse match and switch..."

There is also a lot of "we shouldn't break that" messages, and people reply with "oh we already screwed that up here and there, so it's fine"...

Re: JavaScript Pattern Matching Proposal

#26

Could someone please explain what this could be used for ?

Instead of using if or switch statements to compute a value, you can use a prettier interface.

So this:

  function getStatus(status) {
    if (status === 200){
      return "Success";
    } else if (status === 401){
      return "Fail!";
    }
  }

  var myString = getStatus(response.status);
Now becomes this:

  var myString = match (status) {
    {200} => "Success",
    {401} => "Fail!"
  }

Re: JavaScript Pattern Matching Proposal

#28

Earlier quoted context omitted.

Smooshes the evaluation of an object that can be many different shapes into an easy to understand operation. I think the HTTP response is a great example. It can have many status codes which can determine how you want to proceed with that response. If you've worked with handling HTTP responses, you've most likely implemented some version of a 'match' operation before.

Is not `switch` enough for this?

It's more concise than switch, as well as more powerful (can destructure objects). You can't set things equal to the result of a switch. I find the pattern very convenient.

  let day;
  switch (date) {
      case 1:
          day = "mon";
          break;
      case 2:
          day = "tues";
          break;
      default:
          day = "wed";
          break;
vs

  let day = match(date) {
      1 => 'mon',
      2 => 'tues'
  }

Re: JavaScript Pattern Matching Proposal

#30
post #23

Isn't pattern matching interesting only in a strongly typed environment where the compiler can statically check that you are giving instructions for all possible cases?

No, not at all. E.g. Erlang is built around pattern matching as a core feature even though it's an untyped language.
Post reply on HN