Neil's News

JS Polyfills

31 May 2017

Are you writing a JavaScript interpreter? Are you dismayed by the large number of functions you will have to write in order to support the standard environment (e.g. parseInt, Array.prototype.push, String.prototype.substring)? If so, then here are over 50 polyfills that will save you a bunch of work.

Yes, this is pretty good evidence that I'm involved in writing yet another JavaScript interpreter. It's also the reason this blog has been pretty quiet over the past few months. In the process I've accumulated some wonderful "WAT" code samples for JavaScript. Have fun with these three:

The letter 'ß' is a German equivalent for a double 's'. It also has a capital equivalent, 'ẞ'. In Firefox and Chrome 'ẞ'.toLowerCase() → 'ß' which makes sense. But in Firefox 'ß'.toUpperCase() → 'ß' and in Chrome 'ß'.toUpperCase() → 'SS'. This is an interesting case where toUpperCase and toLowerCase do not round-trip, and different browsers do so differently.

String's split function returns an array of parts, up to an optional limit. For example 'a,b,c,d,e'.split(',', 3) → ['a', 'b', 'c']. But if you want all the parts, Infinity will not do what you expect: 'a,b,c,d,e'.split(',', Infinity) → []

And finally, what does the following code do?

  function foo() {
    for (var i = 0; i < 10; i++) {
      try {
        return i;
      } finally {
        continue;
      }
    }
    return i;
  }
  foo();

For reference, Python treats a 'continue' in a 'finally' clause to be a syntax error. JavaScript does not.

< Previous | Next >

 
-------------------------------------
Legal yada yada: My views do not necessarily represent those of my employer or my goldfish.