My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Monday, June 30, 2014

On Meaningful Performance

This post is a complementary write up about my WebPerfDays talk given at Google HQ last Friday.

Slides And More

During the talk I've live demoed an Arduino Yun board and its performance and I've also showed through a documents camera live performance tests on a wide range of devices including:
  • Android 2.3
  • Bada OS
  • Blackberry 10
  • first ZTE FirefoxOS phone
  • Windows Phone 8
  • ... probably others too ...
While it's easy for me to point at those slides, you'll miss most of the live demoing content so here a better walk through.

Embedded Systems Performance

While Intel's Edison can be considered just a promise, there is already a huge variety of boards based on Atheros AR9331 board which is a single core MIPS architecture based System on a module @ 400MHz almost as small as the promised Edison.
Arduino Yun is only one of those boards featuring such beauty, and here something interesting about performance.

nodejs and npm work but npm is freaking slow

I've also opened a ticket about this non critical issue but the long story short is that npm --version or just npm --info take more than 7 seconds to show anything at all plus if you don't disable node flags npm will crash/fail to install anything with the global flag.
The lesson here in a nutshell: if your program is capable of smaller tasks, isolate these and make these executable/available a part instead of putting any software behavior after loading, parsing, and analyzing the entire logic. --version, as example, is not even something to even think about. Make basic operations available ASAP and lazy load complex operations and related logic only when needed.

nodejs FileSystem can go faster

It does not matter if node fs is asynchronous and non blocking, it still ensures somehow atomic reads and writes and its performance are usually based on assumptions that today Hard Drives have a lot of cache, are very fast ... etc etc ... then you face embedded:

SD cards are actually pretty fast but if you have concurrent reads you won't have any cache to take advantage.
Little tricks like those used in some fspeed experimental module might help to reach better concurrent performance without needing much more RAM or CPU power from the tiny board.

nody little server

The entire talk has been live demoed over my Arduino Yun and nodejs running nody, a tiny little server focused on doing one thing: serving (little) files if presents to as many clients as possible.
nody handled up to 20 devices at the same time, asking for same or different content, without a glitch.
The project with same name already exists in npm so I might think about a new name and make it a proper package ideal for embedded systems. It's KISS and YAGNI at its best so far :-)

Mobile Web Has Embedded Performance

It would be so simple if everyone had the latest iPhone or latest Android Hardware available, unfortunately the reality is way different and specially in emerging markets where cheap phones are the target to reach.

2010 Best Practice still valid

Everything I could do to make this map experiment move smooth even on Bada or Android 2 phones is still valid these days:
  • you might want to degrade to 30 FPS instead of 60 and go smoother in older HW
  • you don't want to cache all the things because you have a limited amount of RAM
  • you might even prefer canvas to draw tiles instead of CSS because canvas is a single surface to upload and draw, CSS squares can be many impacting FPS smoothness/linearity

Benchmark For Real

The Tesla Experiment is a good benchmark to see how good is the GPU, if used at all, the CPU that will calculate all lightning, and how many touch input we can have on a single screen. A cheap old Bada OS perform actually very well in there, why aren't we targeting these devices too?

Do Not Polyfill Old Hardware!

When you realize that simply touch or mouse move events are very heavy and triggered like 15 times per second in old Androids phones, you must be think again why on earth you would use touch events to simulate Microsoft Pointer Events, a kind of event that also won't bring us much on touch devices ...
Windows 8 and WP 8 Phones have a very good hardware and the cheapest WP8 phone you can try will trigger at 60FPS any simulated touch event ... deal with it Microsoft, we need to support old Android and other browsers with its old Hardware underneath, you are the only out there without Touch Events support ... please fix this!

The power of Touch events

Using just W3C Touch Events interface we can create interesting logic for our Web Apps like this 54 cards deck or some horizontal snapped scroll (the second one with the 2 inside, try to move it horizontally).
In order to create these little demoes:
  • ie-touch which is the simple drop-in able to make WP phones react to touch events
  • dom4 to bring common new DOM Level 4 entries tested and normalized for probably the widest variety of mobile phones and OS of the last 5 years
  • ScrollHandler to understand user gestures
  • SimpleKinetic to calculate asynchronously directions and movements through deltas

Performance That Matter For Real

As mentioned during my talk, if you are still using jsperf to benchmark ++i VS i++ you really have no idea what is the problem in your app ... focus on real bottlenecks and try to avoid holding on RAM all that data, all that DOM, all those images, etc etc ... use storages, cache callbacks instead of entire network or i/o results, find the problem and solve it reasonably.
Last, but not least, spend few bucks for some cheap second hand phone and use it for tests: if it will go reasonably well in that hardware, it will FLY in any other modern browser! Don't trust your emulator when it comes to real raw performance.

Get ready for the future: it will not necessarily be more performant, rather smaller, using less power, and everywhere, as the Internet Of Things is already these days!

Tuesday, May 20, 2014

134 bytes for an optimized and very basic jQuery like function

TL;DR this fits in a tweet :-)

What's New Here

The most tiny, common and probably used utility for quick prototyping is usually even smaller:
function $(S,P){return [].slice.call((P||document).querySelectorAll(S))}
but it's a performance killer for all cases where we use #selectors or even body since the engine inevitably needs to check all nodes in the DOM.

The Handy :first Pseudo Selector

Hard to believe W3C preferred two different but similar methods instead of simply adding a pseudo :first selector which is not standard and on top of it, it does not work as :first-child or any other selector ... the purpose would be to select only the first occurrence and stop the DOM parsing in an efficient way; instead we need to use querySelector, which is different from querySelectorAll.

A Consistent Result

Not only two different methods to use, we cannot operate in a similar way with those results anyway since one is collection like, where the length would be the indicator for empty results, while the singular version would be eventually null.

Well, Scratch That!

With desktop and mobile browsers released between 2008 and today we can do already many things using native APIs and here we have a probably not always perfect qSA that might fail using some crazy selector I personally try to avoid anyway, plus many Array extras that today are not extras anymore thanks to any sort of polyfill.
Good news is, we might want to polyfill only for jurassic browsers querySelector/All too ... so here what we can do:
// set all click actions per each link
$('a')
  .forEach(function (link) {
    link.addEventListener('click', this);
  },
  function click(e) {
    // prevent default
    e.preventDefault();
    // and show the link
    alert(e.currentTarget.href);
  }
);

// only first occurrence
$('.logout:first').forEach( ... action ... );

Going Wild Extending

The temptation to extend Array.prototype in order to simplify listeners handling is huge ... but while I am not telling you some library did it already, I'd like to show some trick to be less obtrusive and still super productive:
// simple utility to add an event listener
$.on = function (CSS, parentNode, type, handler, capture) {
  // in case parentNode is missing
  if (typeof type !== 'string') {
    capture = handler;
    handler = type;
    type = parentNode;
    parentNode = null;
  }
  return $(CSS, parentNode).map(function (el) {
    el.addEventListener(type, handler, capture);
    return el;
  });
};

// example
$.on('a', 'click', function (e) {
  // prevent default
  e.preventDefault();
  // and show the link
  alert(e.currentTarget.href);
});

That's Pretty Much It

We have a tiny, yet performant utility, and many ways to make it better for what we need on a wide range of already supported browsers.

Friday, May 16, 2014

serving static files twice as fast in node.js

Having asynchronous I/O does not bring automatically "best performance ever" but it helps already.
However, regardless its amazing performance, node.js is also famous for not being a performant competitor when it comes to serving static files ... is there anything we can do?

Avoiding Multiple Reads

Every time we use fs.readFile we schedule a reading operation. This is non blocking and async, but what happens if two users ask for the same file in a fraction of time between the first read, and the second?
// simulating disk I/O
disk.read.push("file.txt");
  // .. while reading

disk.read.push("file.txt");

<< disk.read.shift();

  // .. while reading
<< disk.read.shift();
Wouldn't be better to have this kind of flow instead?
// simulating disk I/O
disk.read["file.txt"].readIfNotAlready();
  // .. while reading

disk.read["file.txt"].readIfNotAlready();

<< disk.read.shift();
We basically satisfied two read request to the same file at once.

Handled fs.readFile

During the refactoring of a personal project of mine, I've benchmarked the current piece of code:
//!@author Andrea Giammarchi
// @module file-read.js
// Concurrent I/O Handling
var
  // still needed, of course
  fs = require('fs'),
  // single shared module cache
  cache = Object.create(null)
;

// same fs.readFile API
this.readFile = function read(name, then) {
  // already requested, let I/O complete
  if (name in cache) {
    // and notify this callback after anyway
    cache[name].push(then);
  } else {
    // first time somebody asked for this
    // create the collection of callbacks
    cache[name] = [then];
    // perform the I/O operation 
    fs.readFile(name, function readFile(err, data) {
      var
        // grab all callbacks waiting for a result
        list = cache[name],
        // loop over such list
        i = 0,
        length = list.length
      ;
      // after erasing it
      delete cache[name];
      while (i < length) {
        // ditch a boring/slow try/catch
        // and notify all callbacks ^_^
        list[i++](err, data);
      }
    });
  }
};
The code used to benchmark is basically this one:
// bench.js
for (var
  // require another file or 'fs' by default
  fs = require(process.argv[2] || 'fs'),
  i = 0,
  // start time
  t = Date.now();
  // 25000 simultaneous requests
  i < 25000; i++
) {
  fs.readFile(__filename, function () {
    // end time if all requests have been satisfied
    // will be async anyway ^_^
    if (!--i) console.log(Date.now() - t);
  });
}
Here results on my MacBook Pro (lower is better):
  1. node bench.js fs: 505ms
  2. node bench.js ./read-file.js: 19ms

About 25X Faster On Concurrent Requestes!

Which I believe is a good achievement when it comes to static files serving since these files usually don't change often so there's actually no need at all to require them more than once per group of users ...
The best part of it? That an array creation compared to I/O operations means almost nothing for V8 so that even if the file is required only once per time and no concurrent connections are in place, the overall performance will be the same, at least in my Mac, and around 9ms per request.
enjoy

Wednesday, May 07, 2014

Touch Events for IE Mobile

Update Windows Phone 8.1 Update 1 seems to have implemented Touch Events natively.
This polyfill will not affect such version and will still work with IE11 for original WP 8.1 and IE10 for WP8.
There is a weird trend in the US, most websites, frameworks, libraries, etc etc do not consider IE Mobile, even if version 10 and 11 might offers way better experience than old Android 2.x phones, still a consistent slice of the Mobile market.

The Fail Behind PointerEvents

Regardless the good documentation, Microsoft did a mistake about events: it didn't consider simplicity and compatibility over adoption and more over, it didn't implement what was working already for the rest of the mobile world, and still from standards: Touch Events

The PointerEvents Utopia and Failure

There is a very simple reason Touch Events are the preferred and most of the time only choice for mobile web development: patterns between Mouse and Fingers are completely different!
As easy as it sounds, as human being and developer you cannot consider a moving action a generic one ... the mouse moves all the time, except when it scrolls through different mechanisms, while the finger moves only when it's touching the screen with an intentional initial target!
In few words, putting all events inside a single "stream" might sound a good move at first sight, but it's totally messed up the moment you try to use such API to define behaviors for Desktop and Mobile.

Augmented Complexity

Instead of simplifying user intent, touching the screen, and developers / application behavior, we need to maniacally filter every single event and behave differently if it's a Mouse one, a Touch one, a Pen one, or whatever touched that screen or is able to simulate even Multi touches with multiple devices ... in few words instead of two different kind of listeners, the Mouse one and the Touch one, we now need a split logic inside a single listener that at any time could confuse both user and application about the intent.
I honestly don't want or expect users to use both mouse and touches at the same time, so why should I be the one responsible to understand what's going on in my page, instead of the native Hardware/Metal close API which aim should be to simplify the higher level development as HTML and JS is?

Where Touch Events Win

Is very simple, if we set a touchstart event to a receiving DOM node, it does not matter if we then set the touchmove and touchend event in the same DOM node since it will keep triggering as we expect even if the little, medium, or fat finger, went out the initial related node ... we are basically simplifying a well known and annoying Mouse pattern where to drag things, after mousedown, we need to add events to the document because the user might be faster than the DOM moving the mouse and we don't want to deal with bloody never ended events over a drag operation ... right ? Well, try to set pointerdown, pointermove, and pointerup to a generic node and then try to drag it around ... I tell you already you will fail unless you don't change the currentTarget per each event using the document for move and up.

Don't Polyfill PointerEvents To Already Slow Browsers!

There are at least two projects which aim is to standardize PointerEvents for Touch Events compatible browsers ... well, the quick advice here is: dont' do that and the reason is simple: PointerEvents are some sort of over engineered Touch Events that will slow down consistently every cheap Android 2 phone which adoption is way larger than any Windows Phone and which performance are way more compromised by these kind of pointless libraries/polyfills when it comes to what the user meant to do: a bloody swipe or scroll and nothing else.

We don't need to know how much the Pen pressed the screen in that specific point and with which angle, we need to know that granny and mum swiped an article, end of the story for 99% of the cases!

Touch Events for IE Mobile

Taking the opposite direction of already mentioned libraries that I won't link for sanity of the mobile web sake, I've created something that slows down a little bit already modern, fast, good, and snappy Windows Phones 8 and 8.1 devices as I have and use on daily basis, through a repository which aim is to bring the easiness of Touch Events to any Windows Phone without you, developer, changing anything in your code base ... if not just adding ie-touch.js before any Touch Based logic you put in place.

Test Included

Check the source code of the basic test and try to replicate the same behavior with your PointerEvents logic and in a cross Mobile browser way ... I dare you!
After you failed trying to do so, check also my old Tesla multi-touch demo and see how it feels having Touch Events in windows Phones too ... have fun!

Sunday, May 04, 2014

Fixing Java Nashorn __proto__

update these guys react quickly, bug tracking here promptly opened by Jim Laskey: thank you!
all right, you might think __proto__ is my obsession but for f*$#k sake not a single engine got it right so far ... and it's perfectly spec'd in ES6 too so I don't know what is with nashorn here ...
// how to fix nashorn
Object.defineProperty(
  Object.prototype,
  '__proto__',
  {
    configurable: true,
    get: function () {
      return Object.getPrototypeOf(this);
    },
    set: function (proto) {
      Object.setPrototypeOf(this, proto);
    }
  }
);

Are You Asking Why?

Here the answer: nashorn is broken, since it does not expose __proto__ quirks anywhere.
'__proto__' in {} is false
Object.getOwnPropertyNames(Object.prototype).indexOf('__proto__') is a -1 negative
Object.getOwnPropertyDescriptor(Object.prototype, '__proto__') is null
Basically even most common basic features detections for '__proto__' are screwed, so that not a single library can trust its own code ... how cool is that ...

Broken null Objects Too

The worst of the worst comes with null objects, where the infamous property makes dictionaries pointless, not secure, and unreliable ... I start thinking the web world was not even ready for dictionaries, it's taking forever to have a reliable one
var o = Object.create(null);
// it's a null object
// nothing should affect it
o.__proto__ = [];

// but nashorn is brilliant
// as old Android 2.1 phones here
o instanceof Array; // true
Congratulation, you never understood what was the purpose of __proto__

Quick Specs Recap

So, since it's apparently the first rocket science problem ever, here a quick summary of how stupidly simple is the __proto__ spec:
  1. if it's a literal expression, not wrapped in quotes, it defines inheritance at runtime: {__proto__:[]} which is an instanceof Array VS {"__proto__":[]} which is just valid JSON and won't even affect inheritance
  2. if accessed through the Object.prototype, where whatever object that inherits from null should NOT be involved, and where __proto__ has not been defined as own property, it behaves as described in the first snippet I've created to fix nashorn
  3. everything else is an epic fail ... seriously, no difference between o.__proto__ or o["__proto__"] and similar madness, if it inherits from Object.prototype and the configurable behavior hasn't been deleted it passes through that get/set logic ... that's really it!
So please fix this madness once for all ... it's about reading specs and implementing them properly, even if Appendix B of whatever status ES6 is ... or GTFO!
</rant>

Saturday, May 03, 2014

micro-env: a tweet sized enriched environment

Probably the most minimalistic KISS approach to JavaScript environment pollution, micro-env is a funny "do more, with less" experiment entirely based on well known and commonly used APIs where each of them will fit in a tweet or better 140 plain chars once minified ... and not even gzipped!

A Micro Sized Rapid Prototype Development

Everything grouped in main topics per each folder is either a:
  • Basic Polyfill, where some caveat a part, the expected/needed behavior has been implemented
  • Partial Shim, where most common cases, performance, and YAGNI approach won over size
  • Feature, where handy, desired, and not that obtrusive ideas get into the env
On top of this, compatibility with every modern and very old browser has been the key so that migrating eventually to more features rich, complete, less obtrusive and more standard libraries such eddy.js will be painless.
Does it work in your browser or env? Feel free to test ;-)

About Objects

The most basic version includes utilities for any object:
// after including micro-env base.js
var obj = {
  set: function (key, value) {
    this.emit(
      'propertychange',
      key,
      this[key],
      this[key] = value
    );
  }
};

obj.on(
  'propertychange',
  function (key, oldValue, nevalue) {
    // do something more useful
    console.log(arguments);
  }
);

// test it
obj.set('key', 123); // key, undefined, 123
obj.set('key', 456); // key,       123, 456
Handlers creation is performed lazily so no actual RAM, CPU or GC extra work is ever involved until needed. Moreover, being the logic that simple to fit in 140 chars, the direct property will help avoiding memory leaks confining handlers within a single object.

About DOM

The DOM version enriches in a similar way only HTML elements, based to addEventListener and others W3C standard behaviors:
window.on('load', function load() {
  this.off('load', load);
  document.emit('loaded');
});
on, off, and emit do exactly what anyone would expect them to do via DOM nodes ;-)

About OOP Features

The Function is normalized with a partial shim for bind plus it's enriched with two very simple/basic utilities:
// Function#bind
window.on('load', app.init.bind(app));


// Function#inherit
// as utility
function Rectangle() {}
function Square() {}
Square.inherit(Rectangle);

// as inline utility
var Square = function(){}.inherit(Rectangle);


// Function#setPrototype
// as utility
function Person(name) {
  this.name = name;
}
Person.setPrototype({
  age: 0,
  growUp: function () {
    this.age++;
  }
});

// as inline declaration
var Person = function(name) {
  this.name = name;
}.setPrototype({
  age: 0,
  growUp: function () {
    this.age++;
  }
});

About Array

not only indexOf, commonly used forEach, some, every, map, and filter are in place too, and more might come soon as long as it fits in about 140 chars.

All Together

Either for node or browsers, we can easily test these features without requiring massive changes or libraries via a copy and paste based on one of the lightest and also fastest env utility out there ... enjoy ^_^

Tuesday, April 15, 2014

The Dark Side Of Transpilers

It's cool when everyone tells us that we can use modern and future ECMAScript features today, right? Well, here the other half of the untold story, the one web developers might not be aware or just wrongly ignore.

What Is A Transpiler

A pre-processor software that converts a non supported syntax into a presumably supported one, polyfilling as example a slightly different programming language, as it is for CoffeeScript, or bringing new features not deployed and not standard and/or fully approved yet to older browsers, as it is for Traceur "ES.next oriented" case.
It's important to understand I am not blaming any specific transpiler in here and these two mentioned one are just famous examples.

Native Source Map Support Or GTFO

As simple as that, if our target browser, and once again I don't mean the one emulated via Chrome dev tools, based on V8, but the real browser with all its quirks based on that exact version of the JS engine that has nothing to do with what's inside our Chrome or Canary, does not support natively source map, we'll never be able to debug anything in a reasonable way. It will be a tedious and blind guessing process about what's going on in there.
This includes any external library that might pollute the original environment with undesired globals, and/or trying to provide meaningful info, without having a real adb live debug, an iOS live debug or a BlackBerry live debug console possibility.
All these non native, platform and browser dependent version, source map bridges aren't that good ... we can feel free to invest time using these though ... however ...

Remember Old IE Simulators? They Are Back!

As silly as it sound, using a single vendor emulator to pretend we are testing all versions of Webkit, Blackberry, Firefox, Windows Phone or webOS out there is the equivalent of pretending that IESimulator ever worked ... while we all know that to test proper IE we need either the real OS with the real IE installed, being strictly related to OS DLLs too, or at least a Virtual Machine snapshot of that OS with that version. Everything else is a lie, period.
Sadly, when we see all those browsers including iOS and iPhone in our devtool emulator, we must be fool to believe that will be the behavior the same browser will have for real.
Just try to imagine that iOS 7 freezes when you scroll while V8 and Chrome keeps firing events like a charm ... while building our next business model on top of this scrolling behavior ...

Possibly Unaware Transpilers

What if the new syntax is transpiled to a not fully compatible JavaScript? Are we going to fix the transpiler then the logic behind then the browser behavior or ... what? How double difficult is to fix a non considered target browser through a transpiler instead of directly feature detect via JS because we know where and what is the problem?
It's like thinking that an assembly issue came out of gcc compiler and we have to fix either the C syntax or the compiler itself ... can we even think about this scenario when we chose a transpiler?

Performance Upside Down

I know this hurts but it's the sad state of reality. New hardware and new software on top with great new features will perform natively as fast as possible these features ... old crappy hardware with already problematic performance issues, as it is for all Android 2 still out there, all IE < 9 browsers out there, all PC still on WinXP and ... you name it ... the moment we have to wrap everything in order to simulate some native Promise, Generator, spread operator, or arrow function to bind them all, when we all know that bound functions are very slow compared to normal one but arrow as a function shortcut it's going to bind everything no matter what, whatever it is it's going to be slower in already slower hardware and not so optimized software.

CSP Pointless Reports

Last but not least, Content Security Policy report will provide completely pointless reports because of some JavaScript generated by some non JavaScript syntax ... if security matters, this is yet another no-go, if not the main one!

About Optimizations

It came out instantly on twitter but this is another myth ... it does not matter if Emscripten compiles 10X faster thanks to asm.js, if our target browser does not support those optimizations and it actually fails with some modern Math method we are doomed. Transpilers need to know the hosting JS env and cannot optimize upfront, that's the reality once again.
This means that even using C as not supported syntax that will be optimized that much, not necessarily we need to write C to go faster .. actually, if the transpiler optimizes for some engine only, others might have worst performance ... but ...

Yeah, Some Browser Will Benefits

As mentioned initially, it's about target browsers. If we are targeting a browser that should support WebGL and asm.js and perform decently showing Unreal Tournament on the screen, there's no need to care about older browsers ... got it?

I Am Not Pushing Back Progress ... But ...

If new developers in 2014 still need to know these obvious things for most of us on the web, maybe they need to chill out with all this use the future now hype because while everything is awesome and interesting and powerful, somebody still have to support people that don't upgrade phones and PCs every year (or 6 months), and a web that would still like to be available by as many people as possible.

Graceful Enhancement

Or polyfills and meaningful libraries that work everywhere, this is my daily mantra when it comes to develop anything that might be useful ... I have no idea how we are supposed to serve different versions of the same modern standard out there. All I know is that slowly, web development is getting better but we cannot abandon web users because we don't care about slow, inefficient, problematic, and not compatible hardware ... we managed to keep alive IE6 for more than 10 years, now between this, which is wrong, and using a prematurely implemented version of ES7 there is an abyss, which represents the road that web development, IMO, should never take.

I believe the web should be similar to a book, no matter how fancy is the cover and images inside, everyone could read it.
That's how I'd like to keep it whenever is possible and reasonable (effort and target browsers speaking, of course).

Friday, April 11, 2014

All IE Objects Are Kinda Broken

Update III
Microsoft landed a patch to supported browsers, including IE9 up to IE11 Desktop.
It's not clear what's going on with Windows Phone IE, but I'd expect at least version 11 to be patched since AFAIK Surface devices have been already fixed as promised before.
I personally strongly doubt IE9 Mobile in WP7 will be patched too but finger crossed for at least WP8 hoping with the 8.1 update this problem will dissolve as well as on Desktop!
Update II there is a better solution
Update
I had a chance to talk with @jdalton and even before that, @bterlson confirmed me they are already working on a fix for the next version of IE and considering patching previous versions: I've also added a third alternative solution to the problem itself, suggested by the same John David Dalton ... I've talked about this option later on so you can check what is this about.
I've posted out of surprise and gut because I really appreciate all progress IE is doing since version 9 so let's hope this is some sort of balsamic vinegar stain that it'll be washed away soon in as many IE versions as possible.
Now, down to the bug ...
Thanks to @bga_ that forwarded to me the following tweet, things are even worst than expected (but keep reading for possible solutions):

Bug Deatils

All IEs that support Object.create seem to be affected. If there are only numeric properties in the created object and no new keyword has been used to inizialize the same, hasOwnProperty check as well as isPropertyEnumerable will miserably fail.
// a generic "class"
function OhComeOn() {}

var a = Object.create(OhComeOn.prototype);
a[1] = 1;
a.hasOwnProperty(1);       // false
a.propertyIsEnumerable(1); // false
for (var k in a) {
  // EVEN IF APPARENTLY NOT ENUMERABLE
  console.log(k); // will be the string "1"
}

var b = new OhComeOn;
b[1] = 1;
b.hasOwnProperty(1);       // true
b.propertyIsEnumerable(1); // true
for (var k in b) {
  console.log(k); // will be the string "1"
}

It does not matter if I use a number or a string as property name or value, it's exactly the same. The only way to make IE believe there is some numeric property to consider too is the following one:
var a = Object.create(OhComeOn.prototype);
a[1] = 1;

// could be anything that is not numeric
a._ = 1;

a.hasOwnProperty(1);       // true
a.propertyIsEnumerable(1); // true
for (var k in a) {
  console.log(k); // will be the string "1", then "_"
}

Fixed If A Descriptor Is Used Instead

This is where the fun begins, as soon as a descriptor is used, everything is awesome.
var a = Object.create(
  OhComeOn.prototype,
  {1:{enumerable:true}}
);

a.hasOwnProperty(1);       // true
a.propertyIsEnumerable(1); // true
Even if not specified as propertyIsEnumerable, the hasOwnProperty check will be trustable once descriptors are used instead of direct access.
var a = Object.create(
  OhComeOn.prototype
);

Object.defineProperty(a, 1, {});

a.hasOwnProperty(1);       // true
a.propertyIsEnumerable(1); // false

Fixing Only These Cases

Accordingly with above behavior, we can say that if there is such bug, and no descriptor is used, most likely we are safe simply polyfilling the behavior:
// note: NOT suitable (yet!) for dictionaries!
var create = Object.create;
if (!function(o){
  o[1] = 1;
  return o.hasOwnProperty(1);
}(create({}))) {
  create = (function(create){
    function Class() {
      // never forget to free the
      // reference counter
      // to the external proto!
      Class.prototype = null;
    }
    return function (p, d) {
      return d ?
        create(p, d) :
        new Class(Class.prototype = p)
    };
  }(create));
}
With above function, previous examples should work as expected:
var a = create(
  OhComeOn.prototype
);

a[1] = 1;

a.hasOwnProperty(1);       // true
a.propertyIsEnumerable(1); // true
Unfortunately, this is not the only problem we gonna have with such bug ...

Corrupted And Doomed Dictionaries

What we cannot do is to use above snippet to create dictionaries, since this does not work as we expect:
function Dictionary() {}
// this is not the equivalent of null objects
Dictionary.prototype = null;


// here the proof
var d = new Dictionary;
d.toString; // function {} [native code]

d instanceof Object // true indeed

Setting null as prototype value never worked like that so we need to find a solution ... but how ...
  1. adding and deleting a non numeric property won't work (with latest updated we'll see it works with numeric properties though as hack to fix the problem)
  2. using Object.defineProperty per each property would be boring, verbose, and slow
  3. descriptors, if empty, do not solve the problem
There must be a non numeric property in order to have reliable dictionaries, otherwise these won't be reliable as dictionaries using the most common check we all know since ever: hasOwnProperty.

First Possible Work Around: The in Operator

Take that JSLint, the most secure way to have dictionaries that behaves as dictionaries is to use the in operator that does not suffer from this bug.
var n = Object.create(null);

n[1] = 1;

if (1 in n) {
  alert('hooraaaay');
}
For dictionaries only, in seems to be the preferred choice also because these properties will show up in for/in loops, but this will break like a charm:
var n = Object.create(null);

n[1] = 1;

if (var k in n) {
  // the infamous check
  // that will FAIL in IE
  if (Object.prototype.hasOwnProperty.call(n, k)) {
    alert(k); // will never happen!
  }
}
The problem here is that most developers are still not ready to abandon JSLint ES3 era hints and embrace dictionaries in a way that is hybrid with these platform, so here I am with the only possible extra solution.

Second Work Around: The Falsy Property

There is no way we deal on daily basis with empty strings as property, unless we are implementing some other sort of hack. I am talking about a solution based on a property that will NOT enumerate, but will FIX properties check.
For unobtrusivity sake, this property should be also configurable and writable.
var n = Object.create(null, {'':{
  configurable: true,
  writable: true
}});

n[1] = 1;

{}.hasOwnProperty.call(n, 1);       // true
{}.propertyIsEnumerable.call(n, 1); // true

for (var k in n) {
  console.log(k); // will be **only** '1'
  // since '' is not enumerable
}

Above solution seems to better fit in current JS world where properties are usually filtered as if (key) {obj[key] = value} plus all own properties will be most likely checked over for/in loops.
More On The Choice Of An Empty String
If you are wondering what's special about the empty string here the answer: when you use JSON.parse(str, revivalCallback) the empty string or the empty key means that the JSON object is fully ready and that would be the last iteration. Since empty property has such strong meaning for JSON, I believe nobody really use empty strings anywhere and for no reason in any library. I also believe nobody ever wrote an empty property name in JSON but in any case this is not a problem because the fix I've proposed will never show up in JSON.parse since it's both not enumerable plus JSON has nothing to do with Object.create so it's the safest property I could think about.

Update II - Actually Not Needed!

Thanks again to Dmitry Korobkin and his further researches: We have a proper solution that won't require any empty string hack.
TL;DR if we set a configurable number and we delete it the object will behave as expected later on ... so ...

Wrapping Up A Solution

In order to have above behavior and a solution for all normal objects in place, here the modified version of initial script:
var create = Object.create;
if (!function(o){
  o[1] = 1;
  return o.hasOwnProperty(1);
}(create({}))) {
  create = (function(create, configurable, define){
    return function (p, d) {
      var r = d ? create(p, d) : create(p);
      // if already own property, nothing to do
      return configurable.hasOwnProperty.call(r, 0) ?
        r : (
        // adding and deleting the numeric property
        delete define(r, 0, configurable)[0],
        // so that now the object is "fixed"
        r
      )
    };
  }(
    create,
    {configurable:true},
    Object.defineProperty
  ));
}
Above snippet is the less obtrusive when it comes to Object.getOwnPropertyNames since the empty property will never show up, no matter if it's a dictionary or not.
While this is in my opinion the best fix for the problem, there might some performance implication since the internal class of each object won't be shared anymore and this can cause de-optimizations per each created object.
Putting together a solution that fixes the problem and is not obtrusive is AFAIK not possible so here yet another snippet based on both new chain and the empty property.
var create = Object.create;
if (!function(o){
  o[1] = 1;
  return o.hasOwnProperty(1);
}(create({}))) {
  create = (function(create, empty){
    function Class() {
      Class.prototype = null;
    }
    return function (p, d) {
      // if p is null
      // or there is a descriptor
      return p === null || d ?
        // crete via descriptor or empty
        create(p, d || empty) :
        // chain via good old prototype
        new Class(Class.prototype = p)
      ;
    };
  }(create, {'':{
    enumerable:   false,
    writable:     true,
    configurable: true
  }}));
}
The main particular caveat, a part from the empty property that will show up in Object.getOwnPropertyNames when it comes to Dictionaries, although hopefully we don't need that so much over Dictionaries like instances, is that passing an empty object as descriptor might confuse the initialization so ... just, don't.
var obj = create(
  Array.prototype,
  {} // <==== DON'T DO THIS!
);
If we want to be extra sure that with Dictionaries the Object.getOwnPropertyNames won't expose our initial hack, we can tweak that too via:
Object.defineProperty(
  Object,
  'getOwnPropertyNames',
  function(original){
    var gOPN = original.value;
    function notTheEmptyOne(k) {
      return !!k;
    }
    original.value = function (o) {
      return gOPN(o).filter(notTheEmptyOne);
    };
    return original;
  }(
    Object.getOwnPropertyDescriptor(
      Object,
      'getOwnPropertyNames'
    )
  )
);
Above hack might be improved accordingly, but that's just a hint I believe not so necessary anyway.

The John-David's Alternative: Don't Object.create(null)

Since using a Dictionary is somehow a doomed choice due some V8 and old WebKit __proto__ implementation, it might make sense to use something like Set/Map from ES6 or a simple HashMap like object instead:
function HashMap() {
  // (C) Andrea Giammarchi - Mit Style
  Object.defineProperty(this, '_', {value:
    Object.create(null)
  });
}
Object.defineProperties(
  HashMap.prototype,
  {
    // clear all the values
    // returns the HashMap
    clear: {value: function () {
      var keys = this.keys(),
          i = keys.length;
      while (i--) delete this._['@' + keys[i]];
      return this;
    }},
    // delete a key, returns true/false
    // accordingly if successful
    del: {value: function (key) {
      return delete this._['@' + key];
    }},
    // get the value or undefined
    get: {value: function (key) {
      return this._['@' + key];
    }},
    // returns true if present, false otherwise
    has: {value: function (key) {
      return ('@' + key) in this._;
    }},
    // all stored keys
    keys: {value: function () {
      var r = [], k;
      for (k in this._) r.push(k.slice(1));
      return r;
    }},
    // set a value and returns it
    set: {value: function (key, value) {
      return this._['@' + key] = value;
    }}
  }
);
With above like utility we can have a universally safe ES5 Dictionary that will never perform like an Object.create(null) but will surely work as expected.

Who Fixed The Initial Problem Already?

Not so many libraries I know have a fix for such issue, at least jsCore and my latest prototypal one has been updated using the empty string solution for dictionaries.
The purpose of prototypal is indeed to bring inheritance in every browser, included those not even compatible with Object.create so, if the test is green, you are safe from problems and ready to go.

WTF IE !

Well, I have no other words to describe this absurd bug with plain JavaScript objects ... all I know is that old IE always had problems with plain objects too, i.e.
// IE < 9 [[DontEnum]] bug
for (var key in {toString:1}) {
  alert('old IE has never been here');
}

Today we also have this Object.create(proto) bug which is a very problematic one and specially for dictionaries, where knowing that some number has been set as own property to a null object might not even be such an edge case, surely less edge ... although it took years to realize there is such problem!

Please Fix it ASAP IE/Chakra Team, thank You!

Tuesday, April 08, 2014

Down To Legacy

Regardless the fact Windows XP is Death, there are places on planet Earth where the meaning of maintainable, updated, and secure Software is unknown, like in United Kingdom's government offices, as example ... however, the amount of legacy code we have to deal with daily on the web is horrendously high and it's not just IE8 or lower:

Even worst, there are server side based browsers like Opera Mini still floating around 4% of global Mobile market share ... do the Math: Android KitKat is 5.3%, Opera Mini is 4%

A Common Denominator

You might wonder what have Webkit on Android 2.X or 3.X, Opera Mini, and Internet Explorer 8 or lower in common, and the answer is pretty simple: none of them properly supports ECMAScript 5 standard!
This means that most of the code you find around the internet these days looks or behave broken on these browsers.
A culture that I don't approve much these days is also: "but who uses these browsers?" ... which is highly subjective accordingly with the country you live.
Of course if you have your little online shop for your little community in your little town this is not a concern for you, but if you want to be reached by the rest of the world too and without creating problems, instead of showing what you have to offer, you might want to keep reading and pay attention to details on how you can simply make everything usable for these browsers too.

Modern Patterns Down To IE6

Since my latest project, the only one fully compatible with all browsers and servers side JavaScript engines that went at least close to ES5 specifications, included Opera Mini, received only 3 stars, I've realized developers didn't like the ES6 like approach, full of already reasolved, tested, and robust patterns, I've proposed ... so I've used the prototypal namespace to bring to every browser prototypal inheritance in a way similar to what modern JavaScript does.

Meet prototypal

The namespace has two utilities so far, fully tested across all browsers and server side JavaScript engines, able to do few things, but in a cross platform working way:
var create = prototypal.create;

// yes, the null object
// available even in IE6
// and Opera Mini
var obj = create(null);

// inheritance
var a = {
      prop: 123,
      method: function () {
        return this.prop;
      }
    },
    b = create(a, {
      prop: 456
    });
b.method(); // 456
If you think es5-shim solved that for you via Object.create you are wrong since es5-sham is marked as not reliable so here prototypal.create will offer tested portability and reliability across all platforms I could try, down to IE6, Opera Mini, Android 2.X and I bet it should work even on Android 1.X too!
The create interface is very similar to the one used in lo-dash except right now lo-dash copies all properties instead of upgrading the instance where possible so, at least for this case, prototypal should be way faster than lo-dash, assuming properties won't be reused anytime anywhere more than once, which I believe is the most common daily pattern.

Classical OOP Too

I've spent quite a while behind the original Class implementation for modern engine and it did not take much effort to support a less pattern filled version for legacy engines ... so I've put it there too without compromising much the final size, the performance, or the quality:
var Class = prototypal.Class;

var Rectangle = Class({
  constructor: function (width, height) {
    this.width = width;
    this.height = height;
  },
  toString: function () {
    return '[object Rectangle]';
  },
  area: function () {
    return this.width * this.height;
  }
});

var Square = Class(Rectangle, {
  constructor: function (size) {
    Rectangle.call(this, size, size);
  },
  toString: function () {
    return '[object Square]';
  }
});

No Strings Attached

Getters and setters, for compatibility sake we can forget about it. These are very nice patterns, but not the most necessary and to preserve compatibility and performance, we ain't gonna need them ... right?
Is null available too? Well, Class works exactly as create except it extends functions prototypes, if function is the first argument, otherwise it creates inheritance with objects, or null, too:
var Null = Class(null, {
  // some optional method
  // that we might want to inherit
});

var n = new Null;
n instanceof Object; // false
Once again, all of this has been tested basically everywhere and you will rarely find similar compatibility out there.

Not Only ES5: Mobile Internet Explorer

I really have enough bullshit around not supporting IE10 Mobile ... this is not the right place to tell you I have fixed even IE9 Mobile panning simulating touch events but IE10 ... for gosh sake, is a way more decent browser than any Android 2.X!
Why on earth some spoiled developer decided that some library or canvas based game should not work on IE because of his/her lack of understanding of pointer events or inheritance, due silly usage of __proto__ even when not strictly necessary, as I've just demonstrated I can have inheritance in IE6 too in an ES5 similar way, I have no idea!
Remember the 2048 game? It was basically one file to add in order to support IE10 too ... and guess what happened when it finally supported IE mobile?

26 retweets and 16 likes ... I've honestly no memories of last time a tweet of mine has been appreciated that much ... seriously!

Polyfill for Touch Events IE Mobile

I don't honestly know when exactly the modern internet became such a douchebag place where supporting everyone is not anymore the mandatory number 1 priority and people keep telling now and then "who uses it?", all I know is that if you really don't support IE Mobile because of your simplified touch events, you can put this polyfill upfront and deal with it!
Seriously, is that simple! You add the script and magic happens, IE 10 supports Touch events and you know why? Because the proposed PointerEvents Interface is actually superior so it's pretty easy to simulate touches in there, while it's impossible to bring same interface on old Touch API.
Bear in mind, the fact we use Touch API on the mobile web ... is because we are not updated on the current leading specification about touches ... it's not that MS did something wrong, for once at least ...

The Web To The Web!

It's a tendency I keep noticing since a couple of years ... I don't know if it's because people are tired about failing and slow standard bodies, but we should never give up about the meaning of the internet: progress yes, but when it's deadly easy to support an older browser, ask yourself and your business why on earth you are not doing it ... it's your money you are eventually loosing, those users? 4% of 4 billions surfing? Who cares, right?
Thanks for keeping the web reasonably accessible when you can ... I am not saying WebGL should not be used, I am saying except for WebGL that cannot be replaced, think twice before you chose any library or framework that supposes to make your life easier.
IE8 is still a thing, so are Opera Mini, old Androids, Nokia Express on Asha platform, and Symbian ... it would be our fault if these people cannot gracefully upgrade their devices and rather feel left outside the rest of the modern world that cannot wait, even if there was actually nothing to wait for.