1. 2

  2. 2

    This is a standard pattern in Lua, which doesn’t actually support switch statements because you can just write them in this way.

    1. 4

      It’s not just a standard pattern in Lua, but it’s a standard pattern in any lanugage that supports a decent map structure and functions as values. It’s too bad that it seems like it’s being “discovered” again.

      1. 2

        I like these little code posts because they’re useful for beginners learning new techniques and intermediate devs making connections between topics. This one didn’t claim it a new discovery, it just offered a nice walk through the issue.

        1. 1

          I appreciate that and understand that beginners need to learn somewhere. I just didn’t get the impression that there was any “prior art” when reading the article.

          But if you learned something from that article and got a bit of history from here, well, good on ya. :)

          1. 2

            I don’t see too many blog posts that explain where the author learned the information they describe. Whether the author believe it’s their own novel idea, or they picked it up from someone else, it’s hard to say when the post doesn’t tell you. That piece of information seems to be left out more often than not, so it’s hard to judge.

    2. 2

      The object literal pattern only supports switching on strings, because only strings can be object keys. By contrast, JavaScript’s built-in switch statement can switch on numbers too. Though with JavaScript’s type coercion, maybe you could use strings like '39' as object keys and access it with the index 39, but that feels unsafe to me.

      1. 2

        It might “feel” unsafe, but it’s perfectly fine. Here, try this:

        var x = {"39": 13.37}
        1. 3

          I think just further demonstrates why people don’t trust Javascript: to many reasonable, seasoned programmers that shouldn’t work, but it does.

          1. 3

            This works because JavaScript converts the hash keys to string before using it as key:

            > a = 'key';  // String
            > b = 4;  // Number
            > c = {};  // Object
            > d = {};
            > d[a] = 1;
            > d[b] = 2;
            > d[c] = 3;
            > d
            { '4': 2,
              key: 1,
              '[object Object]': 3 }

            This means that even though you can use objects as keys, they will all translate to '[object Object]'.