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

Wednesday, July 24, 2013

IE8 Is More W3C Standard

I know I am probably late for this party but I am re-exploring here and there Desktop web development and developers approach to common Desktop problems.
Pointless to mention that IE8 is probably the biggest one so here I am with some good news!

W3C DOM Level 2 Implemented In IE8

You read that properly, including custom bubbling events!
This is how much this ambitious but overall slim project is about, trying to harmonize IE8 and IE8 only so that we can focus more on standard W3C DOM API without requiring any external library at all unless necessary.

Tests To The Rescue

If you don't believe it or you would like to try it in a real IE8 (no simulated) browser, here the interactive link that will work with all modern Desktop and Mobile browsers plus IE8 thanks to the mentioned library.
The test is interactive in the meaning that at some point an action, a real one from the user, is expected such a click, an input focus or an input blur so that all tests, synthetics and not, are properly tested and behaves as expected.

Readapting W3C Style

The old IE8 gotchas are still there where the most disturbing one in this case is the following:
element.addEventListener(
  'x:event',
  function problem(e) {
    element.removeEventListener(
      'x:event', problem, false
    );
  },
  false
);
Above example will fail in IE8 because of the expression bug that creates an outer scope reference to a declared function. In few words, the assigned method won't be problem but it's referenced expression.
var really = function problem() {};
// only in IE < 9
alert(typeof problem === 'function' &&
  // note these are different
  problem !== really
);
// true
Unbelievable? Well, an old gotcha already demystified where we have 3 easy solutions:
// first solution
var solved;
element.addEventListener(
  'x:event',
  solved = function solved(e) {
    element.removeEventListener(
      'x:event', solved, false
    );
  },
  false
);

// second solution
element.addEventListener(
  'x:event',
  function(e) {
    element.removeEventListener(
      'x:event', arguments.callee, false
    );
  },
  false
);
Well, yes, arguments.callee is still a thing and a very important and useful one in IE less than 9 world: go for it if you are supporting this browser!
A third solution reminded me by David is the following, based on function declaration only:
// third solution
function solved(e) {
  this.removeEventListener(
    e.type,
    solved,
    false
  );
}
element.addEventListener(
  'x:event',
  solved,
  false
);

eddy.js Is Available Too

That's correct, the eddy test page you might want to test with IE8 too should be completely green which means that IE8 could use without problems the eddy.js core library: isn't this awesome?

Thursday, July 18, 2013

eddy.js - A Bold Approach

Not the first time some project of mine ends up in JavaScript Weekly, however this time something different happened since eddy.js reached my top 5 projects list in my personal Github repo in about a week since my first tweet and I've never even blogged about that and: This. Is. Awesome!

eddy.js In A Nutshell

JavaScript is the easiest event driven programming language I know and every library out there knows this too!
jQuery, node.js, these are just the most successful JavaScript API out there and mostly based on event driven development, either with asynchronous API and libraries behind or based on DOM behavior as jQuery is for sure.
eddy.js aim is to bring the ease of an event driven application everywhere, hopefully matching everybody taste in both DOM and server side world too!

Fairy Tales ... Less!

Let's face reality: except for switching the light on or off where .switch() is most likely the most semantic and probably a better method name you could think about for such operation, we are used to think that on is a prefix for any sort of event (onload, onresize, onmouseover, onsomethinghappened) and still .on() is the method to define an event handler in most successful libraries since JavaScript time.
Moreover, switching the light on or or off is really a 1% of time edge case action in web/JS programming since the usual habit is disabled or enabled or, electricity speaking, connected.
OK, OK ... if you are programming some developer board based on relays to switch on or off things, these words could have a bigger meaning for you but seriously, in JS, and since about ever, these have been the way to understand events, and event driven behaviors!

eddy.js To The Rescue

In about 1KB minzipped, eddy.js transforms any object and only if needed into an EventTarget or, in a node.js world, EventEmitter, being absolutely as CPU and memory safe as possible, providing though enormous advantages for any kind of object!
var generic = {};
// OK, at this point I'd love to know if
// this object will ever fire a notification
// no matters what it does
// I just would like to register ... but how?
// wait a second, Hell Yeah, eddy.js!!!
generic.on('hell-yeah', notifyMe);
It's really that simple: the moment we need an event drive behavior, we are sure that any object that inherits from Object.prototype will expose those methods we all love and those will work as we expect! Isn't this much simplified than following code?
// the current node.js way
function PretendingThisIsFine() {}
PretendingThisIsFine.prototype = Object.create(
  require('events').EventEmitter.prototype,
  {
    constructor: {
      value: PretendingThisIsFine
    }
  }
);

// later on
var generic = {};
var boring = new PretendingThisIsFine();

// promoting generic now ... but wait ...
// what if it was already defined?
// this will fail like hell since all
// behaviors related to the object are lost!
generic.__proto__ = PretendingThisIsFine.prototype;
// now generic is not the object we know anymore
// this is not a solution!
So here the good news, trusting a simple 1KB library that could be served in any CDN, above scenario could simply be like this:
// the specific EventEmitter class?
// function YAGNI() {}

// later on
var generic = {};

// whenever we need it ...
generic.on(event, behavior);

Slightly Obtrusive But Totally Pragmatic !

Back in those days where libraries defined new needs for JavaScript as Prototype library and its Function#bind did, we are also in a different time where Object.prototype properties can be extended as not enumerable so that every for/in loop will be safe, how great is that?

... And What About IE8 ?

Yes, as much as I am reluctant to this topic, it's supported!
However, right now only for the JScript part, hopefully pretty soon the whole package with DOM too!
Anyway, if you are here worrying about IE8 and Object.prototype pollution and for/in problems, I've got some good news for you:
  • you are still supporting IE8, you are using obj.hasOwnProperty(key) in every loop so you are safe
  • we are in 2013, IE8 survived from 2009 until now but if today some library will start to pollute in a non enumerable way the Object.prototype that's just OK since your IE8 code should be aware of for/in problem, isn't it?
  • if you think it's too late to spend time refactoring for IE8 ... well, you nede to do that pretty soon regardless so this might be your very best occasion to adopt a simplified approach to event driven development: go for it!

Still Some IE8 DOM Gotcha

I am trying to create a way to obtain, and in way less lines of jQuery code, a unified behavior for IE < 9 so that synthetic events can propagate basically same way DOM events would do there but for any other IE8 based library, eddy.js should be just fine!

Already Compatible

If you add eddy.js after libraries that relies in a weak .on() feature detection, eddy.js will be sitting there for all other objects that did not match library criteria so that eddy.js is tested as compatible against jQuery and all other libraries.
Give it a try, please, and let me know what didn't make you happy, if anything except some old school morality about extending the Object.prototype ... I mean, there are no other ways to obtain same usefulness if not enriching the prototype root, isn't it?
Or maybe you want to go down with this chaotic pattern?

Tuesday, July 09, 2013

Some JS Descriptor Trick

I am back home for 20 minutes after 10 days of vacation in Italy and already bored so which better way than talk about some wizardish trick about JS descriptors? (yes, they were showing again the great wizard of OZ in the United Airline flight from Frankfurt ... thanks for wondering...)

The Recycling Trap

Descriptors can be recycled without problems and reused to define same things here and there. However, there is an undesired side effect about recycled descriptors: these works with constant/static values, getters, or setters, but are unable to change behavior in their lifetime.
var propertiesDescriptor = {
  shared: {
    value: Math.random()
  }
};
Above descriptor is just a basic example where Object.defineProperties({}, propertiesDescriptor) will pollute the empty object with always the same random value.
var a = Object.defineProperties({}, propertiesDescriptor),
    b = Object.defineProperties({}, propertiesDescriptor);
a.shared === b.shared; // true !

Describe A Descriptor With Descriptors

This sounds like a descriptorception and it's actually exactly that one: a property described as property descriptor, able to be different every time the descriptor is used to define properties.
Here how we could enrich the propertiesDescriptor object in order to have a runtime property too.
Object.defineProperty(
  propertiesDescriptor,
  'runtime',
  {
    enumerable: true,
    // a getter is required
    get: function () {
      // so that every time the object
      // is used as properties descriptor
      // this returned value will be used
      // as "runtime" descriptor instead
      return {
        value: Math.random()
      };
    }
  }
);
We can perform the check one mor time now against same code.
var a = Object.defineProperties({}, propertiesDescriptor),
    b = Object.defineProperties({}, propertiesDescriptor);
a.shared === b.shared; // true !
a.runtime !== b.runtime; // true again, hooray!

Non Scalar Only Values: Achievement Unlocked

This is pretty much what we have achieved with latest trick: the possibility to recycle and reuse a descriptor being sure this will hold all static/scalar/constant properties as we wanted, and also create new objects, methods, or features, each time the same descriptor is used to define one or more property.

A Basic Counter Example

Let's say we'd like to know how many times the same properties descriptor has been used during a program lifecycle, you know what I mean ? All together:
var propertiesDescriptor = {
  shared: {
    value: Math.random()
  }
};

Object.defineProperty(
  propertiesDescriptor,
  'runtime',
  {
    enumerable: true,
    get: function () {
      this.__count__++;
      return {
        value: Math.random()
      };
    }
  }
);

Object.defineProperty(
  propertiesDescriptor,
  '__count__',
  {
    writable: true,
    value: 0
  }
);

var a = Object.defineProperties({}, propertiesDescriptor),
    b = Object.defineProperties({}, propertiesDescriptor);

alert([
  a.shared,  // 0.1234
  b.shared,  // 0.1234
  a.runtime, // 0.5678
  b.runtime  // 0.8901
].join('\n'));

alert(propertiesDescriptor.__count__); // 2

Lazy Value But Not Lazy Property

The last example is about creating a descriptor with a specific property that will create a new value once the descriptor has been used with a generic object.
This time is about creating a lazy property value only when accessed through the extended object and not through the property name descriptor ... right ?
var propertiesDescriptor = {
  shared: {
    value: Math.random()
  },
  lazy: {
    configurable: true,
    get: function () {
      return Object.defineProperty(
        this,
        'lazy',
        {
          value: []
        }
      ).lazy;
    }
  }
};

// OR
Object.defineProperty(
  propertiesDescriptor,
  'lazy',
  {
    enumerable: true,
    value: {
      configurable: true,
      get: function () {
        return Object.defineProperty(
          this,
          'lazy',
          {
            value: []
          }
        ).lazy;
      }
    }
  }
);
At this point the object, let's say a generic constructor.prototype, will be described as shared accessor so that each instance, together with the prototype itself, could redefine that property only when accessed.
This is in theory better for memory usage and GC operations but hey ... I've said since the beginning these were just tricks, isn't it?
Sim Sala Bim!

Wednesday, June 12, 2013

On Harmony JavaScript Generators

Developers get easily excited when something so used, acclaimed, and desired in another land comes to their own ... or the one they think they own ...
This is the case of ECMAScript 6 Harmony Generators, something at this time you need to activate through the --harmony flag in node or going to about:flags in Google Chrome Canary url bar and enable experimental harmony/extension.
Once you've done that, you'll be able, still through Chrome Canary at this time, to test examples, benchmarks, and other things in this post ... ready? So here the first great news:

Generators Are Slower

At least two times slower than forEach and about 10 times slower than regular loops.
This is the result showed in this jsperf benchmark you can run too.
Of course generators are slower, there's a massive process behind each generator such:
{
  code: 'the generator function body',
  context: 'the bound/trapped context',
  scope: 'the whole scope used by the generator',
  handler: 'to perform iterations',
  state: 'the current generator private state',
  // inherited from GeneratorConstructorPrototype
  send: 'the method to address values',
  throw: 'the method to throw Errors',
  next: 'the method to keep looping'
}
// plus every 'next' or 'send' call
// will return a fresh new object
{
  value: 'the current value at this time',
  done: 'the boolean value that helps with iterations'
  // when done is true, an extra call
  // to .next() will throw an error!
}

Not Only Slower ...

The fact every interaction with a single generator creates N amount of objects means that the garbage collector will work more than necessary and the RAM will be easily saturated whenever your server does not have such big amount of it ... and cheap hosts are still the most common choice plus if the program/language is greedy, why should you spend more in hosting hardware? You should not, as easy as that.

... But Feel Free To Use Them

If you believe generators can help anything in your logic, infrastructure, system, and you don't need best performance for that situation go with generators. These have been used in Mozilla internals for a while since there when Firefox was version 3 or even lower, can you believe it?
So, if these worked before becoming part of a standard and before hardware was as good as it is today, there must be use cases where generators are a better choice ... right?

JavaScript Never Needed To Sleep !!!

Unfortunately, a part for some academic Fibonacci exercise or even worst some sleep(delay) example, there's no much more you'll find about how cools are generators in JS .. simply because JavaScript never really needed them, being an Event handler oriented/prone programming language, where events always worked even better than generators for other languages since events can be triggered at any point, not just in a synchronous "top-to-bottom" flow.

Coming From Mars

One common problem in JS is that every new comer would like to find what is missing the most from her/his own old programming language ...
  • PHP developers never complained about missing types, they'll rarely get how prototype inheritance works there though
  • Java developers complains about missing types ... they'll try to use the JS flexibility to make it as similar as Java as possible understanding inheritance slightly better than PHP devs and abusing closures by all means to make it as super() compatible as possible 'cause ParentClass.call(this); inside ChildClass constructor freaks them out
  • C# developers think they have all the best there ... forgetting C# is not statically compilable and it is derived from ECMAScript 4th Edition, almost 2 editions before current JavaScript specification ^_^
  • C++ developers will propose new optimized Virtual Machines every day and most likely will probably never use JS ... still they will decide how JS developers should use JS regardless
  • Python and Ruby developers will just laugh about all JS shenanigans thinking their favorite language has none of them or worst
Well, here the thing ... generators and yield keyword are really old concept from languages that have not being created to work asynchronously as JS does, included all those mentioned in above list.
That's why I believe generators aim is being misunderstood from JS community ... and once again, feel free to use them as much as you want, but please keep reading too, thanks!

Queuing The Delay

if you start waiting for events after other events in a generator way:
var file1 = yield readingFile('one'),
    file2 = yield readingFile('two'),
    combined = file1.value + file2.value;
Here the bad news: that won't work magically as you expect!
// a magic function with many yields ...
function* gottaCatchEmAll(fileN) {
  for (var i = 0; i < arguments.length; i++) {
    yield arguments[i];
  }
}

// a magic expected behavior that won't work
// as many might expect ...
var content = gottaCatchEmAll(
  'file1.txt',
  'file2.txt'
);
Until we call content.next(), we eventually store the object value if no error has been threw and the done property is false, no parallel file loading will be performed by all means!
That's correct, what node.js elegantly solved with what JS was offering already, is screwed again with this new approach that won't block and won't execute at the same time.

Still Room For New Users

The controversial part about generators is that these might be useful to synchronize sequential, inevitably delayed or dependent executions while still non blocking other handlers ... well, here a couple of thoughts:
  1. try to make a generator behave as you expect ... seriously!
  2. try to learn how to use a queue instead
Not kidding, the second part is much easier than expected plus is a Promise like approach compatible with every environment and it fits in a tweet.
function Queue(a,b){
setTimeout(a.next=function(){
return(b=a.shift())?!!b(a,arguments)||!0:!1
},0);
return a}

How Does That Work?

I've tried to explain that in details in this working with queues blog post and at the same time I have written a slightly improved queue so that arguments can be passed between callbacks.
var fs = require('fs');
var q = Queue([
  function onRead(queue, args){
    if (args) {
      // add result to the content
      queue.content.push(args[1]);
      // if there was an error ...
      if (args[0]) {
        // attach it to the queue object
        queue.error = args[0];
      }
    } else {
      // first time execution
      queue.content = [];
    }
    // if there's anything to read
    if (queue.files.length) {
      // add "priority queue" to itself
      queue.unshift(onRead);
      // so that once done ...
      fs.readFile(
        // ... reducing the number of files to read
        queue.files.shift(),
        // ... will be re-executed
        queue.next
      );
    } else {
      // simply fire the end of this thing
      queue.next();
    }
  },
  function theEnd(queue) {
    // if there was an error ...
    if (queue.error) {
      // throw it or do whatever!
      throw queue.error;
    }
    // otherwise simply show results
    console.log(queue.content.join(''));
  }
]);

// files to load
q.files = [
  'file1.txt',
  '/user/attempt/file2.txt'
];

OH Come On What Is That

If you think dealing with generators is easier and the real effort behind the yield keyword is less verbose than above abstract example over a single use case, I am here waiting for your link to show me the ease, the cross version/platform compatibility, the performance (and I am not talking about your latest MacBook Air device but hardware Raspberry-Pi like which is suitable and already used as a web server) of your generator based solution willing to reconsider my point of view and change some module in order to switch, even if not needed, to this new approach.
Right now I see this new entry as completely overrated, able to bring fragmentation between node.js and the Web, and unable to concretely simplify or solve parallel asynchronous operations as elegantly as events would do through emitters.
Thanks for your effort reading 'till the end.
Some comment outside this blog:
  • Alex Russel on performance, and my reply which is: bound functions are still slow. I am not expecting generators to be faster than bound functions at any time in the near future

Wednesday, June 05, 2013

ArchLinux Might Not Play Cool

Update

This rant, referred to that time, is still valid. However, the lastest ArchLinuxARM package has been updated after the big change and everything works again as expected. Thanks Arch Linux for updating all packages, appreciated!
I'm actually avoiding a title such WTF ArchLinux to not leave a mark for this awesome community ... I mean, the best of the best: an always updated Linux distro for many devices and architectures blazing fast on boot time and freaking lightweight so you can put any extra you want and nothing more .. how can anyone ask more ...

Kids Play Too Much There

No, really ... this is not about blaming anyone specifically but seriously, a change able to brick every device ain't cool guys, not at all.

Cannot Trust Pacman Anymore

The main tool designed to update your system is screwed for basically every single tutorial about installing Arch Linux I could find on the net. pacman is doomed by an update, philosophically superfluous, able to make the update manager itself a joke.
That's correct, now you need to update all tutorials out there that says that
to update your system, you should simply pacman -Syu and working magic happens
Now every single piece of internet related to pacman or how ArchLinux is updated won't work anymore.

Cubieboard Is Just One

Every single article that will make you happy about installing ArchLinux in this board, or any other, will piss you off if source files you download are before 4th of July 2013 because the moment you can say hooray, it worked and you'll keep following instructions that will tell you best thing ever to do after a successful ArchLinux installation is to pacman -Syu as first command will nicely fuck up all your effort.

Focusing On Something Else

I am a developer and I love tools. The OS is just one of them to me, the one that makes me work and experiment with things I do for working or things I do for myself.
If I cannot trust the fact Linux is there since ever and every related OS is using some rootfs structure that worked without problems untile now, I don't want to find that everything that was using that structure won't work anymore because of some decision that is not practically friendly with any user in the community since it's not compatible with the single package manager the community is using ... I mean .. seriously ... WTF!!!

Just A Haughty Community ?

Worst part is that I was going to humbly open a post in your forum then I've realized to do that I have to register and answer this question in order to do that:
What is the output of "date -u +%V$(uname)|sha256sum|sed 's/\W//g'"?
I've never seen anything dumber that that .. first of all, if that's because a possible robot, most likely runs over Linux and is able to simulate the question wrapped in quotes and produce automatic result, if this was an idiotic robot attempt, secondly because the moment I want register to the forum is probably because one of your community "hackers" did such dumb mistake that I cannot even test my ArchLinux machine anymore ... so, whoever thought that was a good way to welcome your forum members, has a very regular IQ, if not lower than that.

Focus On Something Else

The moment a community with a vibrant and excellent product as ArchLinux is starts wasting everybody time behind these philosophical changes that break everything in facts is the moment the community needs to breath 5 minutes and think what the hell is going on and what's really needed to make the community better instead of pissing everybody off about some decision that no matter if was OK and right, it should NOT have broken all users around that were trusting the package manager to simply work as explained and emphasized everywhere on the WEB
Apologies for the rant but ... bloody hell, I've got all my boards screwed because of this "little change" in the whole OS.

Even Dumber

The page that is telling us how to update things is suggesting
# pacman -Syu --ignore filesystem,bash
# pacman -S bash
# pacman -Su
... too bad the current latest updated pacman cannot be installed without the updated bash too ... congratulations!

Saturday, June 01, 2013

The node.js Relative Path Case

Right now, it sucks because ___, as @izs told me to start with, I could not find a simple way to resolve a path from a module that exported a function into another one.
Spoiler: the reason I am trying to resolve paths is to load fresh modules runtime in polpetta. However, this might be a bad practice.
@WebReflection Lest I commit malpractice, I must tell you this is a terrible idea. Now warned, rock on with your bad self. Hack away :)
Still, my point is that it might be handy to be able to resolve paths relatively form the invoker regardless the why, even if you should always ask yourself that ;)
This case is quite easy to misunderstand so I'll skip extra explanations now and put down some code.

relative.js

This example file aim is to log ASAP two different path resolutions: the one from the path, passing through the process.cwd(), and the one from the relative.js file itself.
Object.defineProperties(this, {
  parent: {
    get: function () {
      // used later on
      return module.parent;
    }
  },
  resolve: {
    value: function (path) {
      // it will resolve from this file
      // not from the invoker
      return require.resolve(path);
    }
  }
});

// path module resolves relatively
// from the current process.cwd()
console.log(require('path').resolve('.'));

// require resolves relatively from
// the current file
console.log(require.resolve('./relative.js'));
Running this from node terminal will most likely show something like:
require('./test/relative.js');
/Users/yourname/code
/Users/yourname/code/test/relative.js
Neither logs or resolution are actually OK if we would like to resolve relatively from that path.
If we would like to use that module method, talking about the resolve() one, we cannot trust the current path.
// will throw an error
require('./test/relative.js').resolve('./test/relative.js');

// will pass
require('./test/relative.js').resolve('./relative.js');
If we install that module through npm as global, or even local in some super folder, gosh knows where we should start the relative path resolution accordingly with the module itself, you know what I mean?

Being Relative To The Invoker Path

In order to be able to resolve relatively from the invoker, we need to know at least where is the invoker.
Thankfully, this is easy but be aware of the caching problem:
// relative.js
var
  path = require('path'),
  relativeDir = path.dirname(
    module.parent.filename
  )
;
this.resolve = function (module) {
  return require.resolve(
    path.join(relativeDir, module)
  );
};
At this point we can invoke the method as expected without having erros, from the process folder.
// will log the right path
require('./test/relative.js').resolve('./test/relative.js');
Good, we are able to resolve module names, problem is ... only from the very first one that required relative.js due module caching so that module.parent will be one, and only one, for any other module.

A Hacky Solution

In order to avoid the caching problem within the required module itself, I came up with such trick at the end of the file:
// .. same content described above ...

// remove the module itself from the cache
delete require.cache[__filename];
In this way every single module that will require('./some-path/relative.js') will have a fresh new version of that module so that module.parent, and its filename, will be always the right one: how cool is that?
I am able to resolve relatively from any outer module its path the same way require.resolve(path) would do inside that module which is exactly needed and the goal of require-updated so that any module can use paths as if these were resolved from the file itself in order to require some other file, relative, absolute, or globally installed.
Still I believe there should be a better way to do this ... what do you say?

Thursday, May 16, 2013

Object.setPrototypeOf(O, proto) IS in ES6

This one is a short one, just to confirm that finally Object.setPrototypeOf(obj, proto) made it into ES6.
The section 15.2.3.2 speaks clearly:
15.2.3.2 Object.setPrototypeOf ( O, proto )
When the setPrototypeOf function is called with arguments O and proto, the following steps are taken:
  1. If Type(O) is not Object, then throw a TypeError exception.
  2. If Type(proto) is neither Object or Null, then throw a TypeError exception.
  3. Let status be the result of calling the [[SetInheritance]] internal method of O with argument proto.
  4. ReturnIfAbrupt(status).
  5. If status is false, then throw a TypeError exception.
  6. Return O.
Without going into details, the most basic polyfill woud be like this:
(function(O,s){
O[s]||(O[s]=function(o,p){o.__proto__=p;return o})
}(Object,'setPrototypeOf'));
If you want to go into details, the full reliable polyfill is hard to write down due all inconsistencies across JS engines out there where the __proto__ setter cannot be reused which means it's not possible to trust this magic over objects created from null.
All you need to do is forget __proto__ and use the suggested polyfill until the day __proto__ can simply disappear from those specs pages.
Enjoy!
This is a full polyfill with some extra info you might want to analyze, whenever ployfill is strictly true or false.

Saturday, April 27, 2013

Few Modern JavaScript Inconsistencies

While the JavaScript weekly mailing list still points to 90s style articles about the old JavaScript Internet Explorer 5 was supporting too, the current world has different real problems to consider.
Here a quick list of things you might not know about the current status of JavaScript possibilities.

Reserved Words As Properties

Number one of the list is the myth that reserved words cannot be used as properties. Here platforms that cannot:

  1. iOS 4
  2. IE less than 9
  3. Android less than 2.1

So, basically, 99% of mobile browsers support properties such obj.delete(), used in most recent JavaScript specifications, while those jurassic browsers need the obj['delete']() convention.

// exactly same good old ES3 behavior
// using ES5 capabilities
Function.prototype.new = function () {
  var
    // grab the prototype
    p = this.prototype,
    // create from it
    o = Object.create(p),
    // invoke the real constructor
    r = this.apply(o, arguments);
  // if the result is not undefined or null
  // and the returned value is an object/function
  // overwrite the result
  return r != null && (
    typeof r === 'object' ||
    typeof r === 'function'
  ) ? r : o;
};

// you can be Rubyish now ^_^
var instance = MyClass.new(1, 2, 3);

// P.S. if you have problems with JSLint
// and the r != null part in above snippet
// it's just time for you to upgrade to JSHint

Please Do Not Support Too Old Browsers

As easy as that. As a developer, company, software provider, whatever, you are trapping yourself behind problems that will never be fixed in those browsers and you are limiting your customer too, embracing development for such old environment, instead of promoting an update that will benefit them in terms of both potentials, expenses, and security.
Any company that will say no to that should be kindly be abandoned, IMHO, they're already out of web/JS business and they don't realize yet.
I understand some graceful measurement should be taken in order to migrate old users, but as long as they feel confortable, they won't migrate sooner for sure.
Customers or people we'd like to let them access our service, should be informed somehow of new possibilities too.

Apple Drops 3 Years Old Software Too

If Apple not accepting non retina software anymore is not enough as an argument, think how many possibilities you are dropping to your software in order to work the same in those old browsers.
You chose Web technologies, you should catch up with these, end of the story.

Object.defineProperty() *Is* Available

Even my Palm Pre 2 webOS supports Object.defineProperty(), together with Object.defineProperties(), Object.getPrototypeOf() and Object.getOwnPropertyDescriptor()!
If you don't want to deal with all this verbosity but you like the power behind, redefine is really your best friend then!

The most widely adopted list of ES5 features down to Android 2.1 phones and webOS are:

  1. Object.create()
  2. Object.defineProperty()
  3. Object.defineProperties()
  4. Object.getOwnPropertyNames()
  5. Object.getOwnPropertyDescriptor()
  6. Object.getPrototypeOf()

Things like Object.freeze() might have been introduced later on so don't trust them ... but, whenever you wanna try that:

var freeze = Object.freeze || Object;
freeze({}); // frozen where possible

function returnFrozen(object) {
  return (Object.freeze || Object)(object);
}

As it is for "use strict"; and all other things that works best natively, above technique will work with Object.seal(), Object.preventExtensions(), and why not, a shimmable Object.isExtensible()

'isExtensible' in Object || (function(){
  // no way ES3 can prevent extension so ...
  Object.isExtensible = function (object) {
    // ... if an object, it's extensible
    return object != null && (
      typeof object === 'object' ||
      typeof object === 'function'
    )
  };
}());

Function.prototype get caller() {return WTF}

Generally speaking the caller property works since ever but there are cases where it does not and this is iOS5 and lower fault.
What am I talking about? About caller over getters, with or without __defineGetter__ old style approach, the new one fails too ^_^
Bear in mind iOS 5.1 and 6.0+ are just fine so you can still use that magic, if needed.
Note a part, that magic ain't disappearing any time soon so ... go on, use caller until there is an alternative: so far, not a single one ^_^

Function.prototype.bind()

It took literarily ages for WebKit to adopt this method so this is something available in all modern browsers but most likely not available with not so old mobile one: easy shim from callerOf!

(function (P, l) {
  'use strict';
  if (!P.bind) {
    P.bind = function (s) {
      var
        c = this,
        a = l.call(arguments, 1);
      return function bind() {
        return c.apply(s, a.concat(l.call(arguments)));
      };
    };
  }
}(Function.prototype, [].slice));

This is the kind of code that I would like to see in CDN, not just 50K libraries for client sake!

Avoid __proto__

Not only conceptually an error and used only to gain some arguable performance boost, __proto__ is absolutely something that IE 10 and 9 will never have in a consistent way.

If you want to transform a list into an array, just var slice = Function.call.bind([].slice); so that you can slice(whatever, optionalIndex) ALL the things, right? The bind() is there and costs nothing ... just use it!

Better Than Zepto

What this library is doing, except from ignoring IE as a Mobile browser, is a poor/quick&dirty design/convention to obtain a prototype swap instead of initializing things in the right way.
The previously linked code could be represented by exactly the same syntax:

// an IE9 and 10 compatible zero bullshit Zepto core
var emptyArray = [];
zepto.Z = function(dom, selector) {
  var result = Object.create($.fn);
  emptyArray.push.apply(
    result, dom || emptyArray
  );
  result.selector = selector || '';
  return result;
}

While performance might not be that good in some engine, and everybody knows that you should never $('select') twice per collection so actually, considering above snippet goes 400.000 objects per seconds, that's not a big/real deal at all!
If that is, I tell you something else is wrong in the app logic!
In any case, actually, there's some mobile platform there, those Zepto thinks is supporting, that scores more with lower results than with a prototype swap, which is the most common selector case, BlackBerry 10 is 8 thousands operations per seconds there compared with __proto__
Thomas Fuchs has been so nice in his repository I cannot even push/contributes these improvements ... surely he would get this one as an insult too, isn't it?

A Swap Oriented __proto__ Attempt

Assuming you still want to swap runtime classes because you cannot define a proper inheritance upfront, here a broken attempt to do that in IE8 and lower:

object = dunder(object, proto);

what's dunder()

dunder() is my attempt to bring a friendly cross platform way, included older IE, to swap proto at runtime.
It requires an assignment so, back to Zepto example, return dunder(dom || [], $.fn) would be all you need to make it work everywhere.

JSON.stringify(object, *replacer*)

This is Safari specific gotcha, and it's about the replacer.
While specs say that Let newElement be the result of calling the abstract operation Walk, passing val and **ToString**(I), Safari will send to the receiver the number 0 instead of the string '0'.
What's the big deal here? That in JavaScript, 0 == false while '0' == true so ... if you have this kind of check in your receiver thinking that if empty, nothing should be done:

if (key) {
  // parse your value
}

Improve that check with if (key === ''), probably the only place on earth where JSLint would have helped you for real instead of messing up your own code.

And for today, that's all folks!

Wednesday, April 24, 2013

Boot To Node.js In 7 Seconds On Arch Linux

This is a long story that started with me buying a Raspberry Pi with the goal of discovering how good performance could have been in such device used as dedicated server.
The story goes on with pcDuino too, and tricks you might want to know about booting up and building node on them.

Why A Pi As A Server

The story of computers is not actually that fair for same computers, as not fair is the Moore's law itself.
Bear in mind, I am not saying that's not working, all I am saying is that if in 6 months we've got double amount of transistors in some CPU, this does not mean we've been used the previous CPU at its best for last 6 months!

Gaming, immortal, consoles such PS2 can describe better than my words what I am talking about: hardware is good until what you need does not fit under that 100% of potentials!

ARM Is Powerful

Not only is becoming one of the most ambitious target for any Operating System, probably including Microsoft, ARM is also both powerful and power consumption aware, something we've never rarely thought about before .. I mean, a server that does not need much electricity so that if some blackout happens it does not dry whatever counter blackout part is playing in the building? And what about a web farm?

A Raspberry Pi Web Hosting Colocation

Yes, it's not just me, and actually ... WTF!
When I've invested a bit of extra time trying to have up and running my own idea of a co-location, raspberrycolocation.com was born instead and sold out ... gosh I'm always late at the party!
What this smart guys did, is to offer a full server for about $50, being absolutely the most competitive dedicated server company in the world right now ... that's as easy as that .... but ...

Arch linux

What those guys offer is a colocation for your own Pi, a device I honestly would never put into anybody else hands (and that's the feeling you have when that little thing works as hell with awesome performance under your own software) over the Raspbian distro, surely a stable, well tested, etc, etc linux based OS, unfortunately kinda/"slightlier" heavy :(
R-Pi aim is to be a cheap replacement for a PC and in this case Raspbian is the most suitable distro you have there.
However, if you are planning to do something different that does not requires a GUI, and RAM is only 512 there, or any other extra thing on top, Arch Linux becomes the best alternative for this device.

The part I love the most about Arch Linux, is that it basically embraces my same philosophy when it comes to JavaScript or, generally speaking, programming with dependencies .... the less I have and the more I know about the app, the faster I move when it comes to add something, fix something, or experiment! (you should try this approach instead of putting, as example, jQuery or Zepto by default in your web page, it works, trust me!)

Living On The Edge

This Aerosmith song is probably looping inside any Arch Linux contributor, as this distribution is nothing about having frozen modules that pass some test and until tested everywhere else will never work, this distro is about having always the latest available software in your system, which will result in a freaking cool, always updated one, as ready for production as much as your node.js project or website is ... I mean, isn't modern JavaScript culture about serving what's the best thing available today? I love that too!

410+ MB of RAM

You don't need me to try the Raspbian distro and check how much require('os').freemem(); command will return in node pre 0.11.2, you can install the package instead of compiling it on the hardware as I am doing, and do the math.
If the device has 512MB of RAM, 410+ after OS booted in about 8 seconds ain't that bad, right? And I am sure the distro coul dbe even more minimalistic ... as it is, as example in the following platform:

The Allwinner 10

If I have to be honest with you, I would rather consider this platform, or any of its new derived, more than a Pi.
I know, kids price not so friendly, but here you have an ARMv7 with most likely at least 1Ghz of clock speed and 1GB of RAM over some NAND which is alwas faster than inboard SD controller (I'll come back on this part too)

The pcDuino Case

As example, you can have an Arch Linux distro able to boot up in 6 seconds into node.js, with an average of 0.3% of CPU usage via SSH to monitor what's going on behind the top scene!

If you try to do the same with the minimalistic full Desktop version of Ubuntu for this device, you'll notice at least 6 to 9% of default CPU usage because of the graphic OS, plus 691511296 of available RAM after boot against a require('os').freemem() resut of 797020160 for the Arch Linux headless distro .. yeah, you heard that right!

Slow Down, You Punk!

While Raspberry Pi has a pretty decent and complete image of Arch Linux that includes all hardware activation at boot time, no led excluded, pcDuino is kinda "problematic" as any Allwinner platform is because of the not so stable graphic videos ... who cares indeed!

If your goal is to have a dedicated server on the palm of your hand, the graphic whatever is something you won't care at all. I agree this might sound confusing at the beginning, if you are not familiar with linux bootable distros, but hey ... the video is such a pain in your spine I am not sure you really want to know how to fix that, do you?

Install Arch Linux In Allwinner A10 ARM Devices

This post and its welcomeness are kinda the beginning of the story about Arch Linux.
What you think makes sense for an OS ... well, you are already out of sync: Arch is kinda the skeleton of that OS, anything else is your choice/matter/problem/duty, if you want to support that platform.

Even More Annoying

Is not just the fact if you are noob in *nix world you should drop this distro by default since nobody wants to deal with you, the instructions, even if you are part of that world, are kinda crap too.

Thank You André

Despite André post talks about a different A10 board, the used code is clearly something you might find handy, once re-elaborated as such:

In my case I had to:

sh a10.sh /dev/sdb pcduino-bootloader.tar.gz pcduino

after changing things might be different for other A10 boards.

As Result

I've been impressed by polpetta performance, as generic hard drive surfer/common intra-cloud, on a network of 15+ devices: not a glitch over these platforms under hand compiled node.js 11.2 versions.
The average ping for this device in the network is 1.3 milli seconds, which is nothing!
Are you sure your initial web business demands much more as dedicated server?
What if a $40 dollars board plus SD card is all you need, to measure your startup success?

What's With SD Cards

The situation around SD Cards is awkward at least. So here the thing, I haven't spot any difference between an 8GB Extreme Pro SanDisk micro SD Card, and an Ultra 32GB version of the micro usb card ... but more over, I don't think you need such amount of space for any of these devices since even looping through FileSystem tables has a cost I believe your cheap ARM dedicated web server should not take into consideration ;)

Have fun with hints on the web about how to build your first dedicated web host in no more than $100 for years, network a part!

Sunday, April 21, 2013

The __proto__ Comic

© all images from ragefac.es and some from knowyourmeme
Being a comic, sentences are not all real, mostly made up for this post.

TC39

WTF is this shit?!

es-discuss

The community needs it and the de-facto library with stars on github uses that instead of [].push.call(new SimplifiedDOMShit, NodeListResult)

TC39

OK, here what we can spec ... making it configurable, so that shit can be dropped at any time in any module

es-discuss

Community, we are going to spec __proto__ shenanigans all over so that any environment will have a special property able to cause more disasters than what eval did before: you should appreciate!

community

so, proto gonna be standard we don't have to change those 2 lines of code?!

me plus some other

what kind of horrible decision is this?

es-discuss

de-facto is de-facto, people use this, people want this! IE ... who cares !

just me

OK, probably this is just a massive misunderstanding between what's truly needed, and what should be proposed ... let's try to fight back in es-discuss ...

es-discuss

You don't understand, you are late, even if not spec'd yet, you are really late

just me

I gonna show you that JavaScript developers understand this is a no-go and it's bad for the language they use on daily basis as bad, and even worse than boring hasOwnProperty check has been for all these years!

still me

Hello Zepto, somebody thinks we are all bigots unable to make simple changes ... here the patch for you repo, it's green, it works, it has no side effect, it demonstrates we are not bigots, what do you say?

Zepto.js

You White Knight bla, bla, bla ... horse shit bla ...

just me

WTF? I can't even explain myself there, they blocked me ... what should I do?

still just me

... well, I gonna see if at least node.js community, with much more unified environment, would accept a proposal...

still me

Hello node, here a patch that is waiting for a patch in V8 so the patch gonna patch the patch, what do you say?

node.js

We don't extend the language and we don't impose coding standards on our users.

again me

Will you consider at least this .. or that ... ?

again node.js

But we're not going to float a patch that adds this feature to V8

still just me

... well, I gonna see if at least V8 will accept my flag that gonna affect node at startup ...

V8

Well, I don't know if V8 will ever accept my patch (update: they didn't ... if in specs, V8 is ignoring Object.setPrototypeOf while IE11 put it there as native function) but actually there is no reason to not accept it, it does not change anything in core, it does not affect anythign around, is something that if explicitly set, enable something that might be specified like that in ES6 in any case so together with all harmony flags and stuff usable when you run d8 or node, what could possibly go wrong?
Let me hope, at least, this is not a conspiracy against my mental sanity ... and if you star it it might go in before node 1 is released, thank you!

sad thing is, Zepto patch was not affecting Zepto performance or logic, neither was breaking things.
Same thing was for node.js, so I started doubting JS community is able to be proactive when it comes to decisions made somewhere else and for the community.
Developers are pragmatic, they use what's available at that time. If this means create a standard out of it, JavaScript will be anarchy and not a language anymore.
And this, my friend, is unfortunately a specifications circle that is not bringing only good things to the JavaScript as your favorite programming language.

Playing With V8 Native And JavaScript

What my Don Quixote like adventure against __proto__ gave me, if nothing, is a better understanding about how V8 engine internals work and how to bind JavaScript to native and vice-versa.

Please Note

Nobody told me anything I've written in this article is true. These are all assumptions after pushing a patch to V8 and learning by mistakes, compilation errors, and "code around reading", done in a couple of hours so apologies in advance if some term or some concept is not perfectly and deeply explained.
Let's start with this!

JavaScript In JavaScript

This was kinda surprising to me, almost the whole ECMAScript is implemented in JavaScript itself.
In few words, what V8 does is not something like Rhino, reimplementing the whole language via a statically compiled one as Java is in Rhino case, V8 is rather the compiler for the specific ES syntax, following an example ...

JSON In JavaScript

It's funny when we compare in jsperf json2 vs native vs jQuery.json vs json3 etc etc, knowing that V8 native JSON is 90% JavaScript, isn't it?

// just a chunk/example from V8 JSON
function JSONParse(text, reviver) {
  var unfiltered = %ParseJson(TO_STRING_INLINE(text));
  if (IS_SPEC_FUNCTION(reviver)) {
    return Revive({'': unfiltered}, '', reviver);
  } else {
    return unfiltered;
  }
}

Above snippet is simply a compact one with few things non common in Javascript: %PrefixedFunctions(), and UPPERCASE_FUNCTIONS().
These could or could not be bound in any V8 JavaScript files and we can see these JS files are those that will create the JS environment we are going to use but let's see how those special things work, OK?

Interoperation Between C++ And JavaScript

runtime.cc and runtime.h files are dedicated to, as the name suggests, runtime JavaScript calls into C++ world.
The runtime.js files contains instead many JS functions used internally to satisfy ECMAScript specifications but not exposed to the outer world.
Bear in mind latter is not the only file that has not exposed JavaScript, while everything that will go out is defined at bootstrap, as you would expect, per each global context (here why two sandboxes have different native constructors) and you can find it in the bootstrapper.cc file.
Scroll a bit, and you'll see how all known Array, String, Boolean, etc, are initialized, while in array.js you can see how the prototype is created: it's again a mix of native and JavaScript, passing though macros!

How To RUNTIME_FUNCTION

RUNTIME_FUNCTION(
  // return type, for JS interaction
  // will be a MaybeObject* one
  MaybeObject*,

  // the exposed %DoNotExposeProtoSetter()
  // function in the hidden JS world
  // behind the user available scene
  Runtime_DoNotExposeProtoSetter
) {
  // isolate pointer is necessary to access
  // heap and all JS types in C++
  // even true or false are a specific type
  // we cannot return true directly, as example
  // or the type won't match
  NoHandleAllocation ha(isolate);
  // in this case, returning true or false
  // does not require allocation or new objects
  // we can simply use what's already in the heap
  return FLAG_expose_proto_setter ?
    // this is a flag defined at d8 launch,
    // I'll go there too
    isolate->heap()->false_value() :
    isolate->heap()->true_value();
    // returns a JS false or a JS true on
    // %DoNotExposeProtoSetter() invocation
}

Above function is the same I've used for the patch, it does not accept a thing, it checks a generic program flag and returns true or false accordingly.
As every developer with a bit of C background knows, when a function is declared, it should be defined in the file header too, so here the runtime.h declaration:

  /* __proto__ Setter */ \
  F(DoNotExposeProtoSetter, 0, 1) \
  \

F is the common shortcut for RUNTIME_FUNCTION_LIST_ALWAYS_N while the first argument is the length of accepted arguments, -1 if unknown or dynamic.
The second argument seems to be a default for all functions, stick with 1 and things gonna be fine.

Dealing With JS Objects

My patch has a quite simplified signature, if you are aiming to accept and/or return objects, you should do things in a slightly different way, here an example:

// function call :-)
RUNTIME_FUNCTION(MaybeObject*, Runtime_Call) {
  // required to handle the current function scope
  HandleScope scope(isolate);
  // arguments are checked runtime, always
  ASSERT(args.length() >= 2);
  int argc = args.length() - 2;
  CONVERT_ARG_CHECKED(JSReceiver, fun, argc + 1);
  // the `this` context :-)
  Object* receiver = args[0];

  // If there are too many arguments,
  // allocate argv via malloc.
  const int argv_small_size = 10;
  // now you know, functions with more than 10 args
  // are slower :-)
  Handle<Object> argv_small_buffer[argv_small_size];
  // ...

  // in case it needs to throw an error ...
  bool threw;
  Handle<JSReceiver> hfun(fun);
  Handle<Object> hreceiver(receiver, isolate);

  // the result, could be undefined too,
  // which is a type indeed
  Handle<Object> result =
      // note, threw passed by reference
      Execution::Call(hfun, hreceiver, argc, argv,
      &threw, true);

  // do not return anything if there was an error
  if (threw) return Failure::Exception();

  // eventually, we got a function.call()
  return *result;
  // don't you feel a bit like "f**k yeah" ?
}

I've removed some extra loop for malloc but basically that's the lifecycle of a JavaScript call invocation.

What About Macros

macros.py contains some (I believe) highly optimized and target specific (x86, x64, arm) function, able to use %_CPlusPlus() functions, and containing most common/used functions across all JavaScript APIs such IS_UNDEFINED(obj).
It also contains many constants used here and there such common date numbers:

const HoursPerDay      = 24;
const MinutesPerHour   = 60;
const SecondsPerMinute = 60;
const msPerSecond      = 1000;
const msPerMinute      = 60000;
const msPerHour        = 3600000;
const msPerDay         = 86400000;
const msPerMonth       = 2592000000;

Dunno you, but I find myself often writing similar variables so I wonder if we should simply have them as public static Date properties ... never mind ...

d8 Options And Flags

To complete my journey into V8, I had to set a --expose-proto-setter flag into d8, which is the command line tool or the dll what you'll have after a successful build of the V8 project.

flag-definitions.h is basically all you need to define a runtime flag providing a decent description that will show up if you d8 --help:

DEFINE_bool(
  // the flag name
  // d8 --expose_proto_setter
  // OR
  // d8 --expose-proto-setter
  // is the same
  expose_proto_setter,
  // the default value
  false,
  // the flag description, better if meaningful ...
  "exposes ObjectSetProto though __proto__ descriptor.set")

In order to access that flag in runtime, do not forget to prefix it as FLAG_expose_proto_setter.
Remember, even a simple value as boolean is cannot be handled like that in JS so check again the RUNTIME_FUNCTION example.

Building V8

There is a V8 page specific for this task, all I can add here is that make x64.release is the fastest way to have a ./out/x64/release/d8 executable and start playing, at least in most common/modern PCs or Macs.

And That's All Folks!

I know it does not seem much, but this article covers:

  1. how to define a launch-time flag for d8
  2. how to interact with C++ bindings for JS code
  3. how to optimize some macro function
  4. how to understand magic V8 JS syntax
  5. how to manipulate, create, change, augment, natives and their prototypes
In few words with these steps anyone could write her/his own version of JavaScript, relying in a robust, extremely fast, and cross platform engine, able to also interact with PHP or other languages.
Bear in mind I am not suggesting anyone out there should start subfragmenting V8, I am sayng that if you need a very specific thing in the environment for a very specific project, you should not be scared by changing what you need and you can also help V8 to be better trying changes directly without just filing bugs: isn't this what Open Source is good for too?

I hope you enjoyed this post, have a nice day!

Friday, April 19, 2013

A Journey To V8 ObjectSetProto Native Function

Update ^_^

whatever story you are interested about in this post, one is that I've proposed a patch to V8 engine (please star it so it gets in faster) to accept a --expose-proto-setter flag at runtime able to expose the proper __proto__ setter so that my node JS pull request could start warning modules using __proto__ instead of Object.setPrototypeOf(target, proto).
What can I say ... open source is beautiful, you can potentially patch everything you want for anything you need ... even behind stubborn, politics, or decisions nobody agreed on :P
Now back to the original post ...


first thing: I write HTML manually in the textarea instead of Markdown, yeah!!!
Why? 'cause nobody on the internet moves fast ... really, no-bloody-body!
so ... back to manual tags writing instead of broken meaningless layout created via magic html editor ... yeeeeeeah!

The Story ...

I know this is getting boring and annoying, and I swear I wish I could say it's the last post but every day there's something more and this story is getting both entertaining and ridiculous!
I gonna tell you how I ended up blocked in Zepto.js repository, and how the rest of reasonable developers are acting instead.
This time, the experiment, is me reporting this story and nothing else. I give you links, I give you facts!

Quick note: they keep telling me I should let it go, but "I cannot sleep anymore" because of this so here my attempt to describe the whole story! Have a coffee, some new tab link to click and dig into, and please, please, keep reading ... also because you might realize ...

It's Not Just Me !

Isaac Z. Schlueter, the man behind node.js, twitted this

@littlecalculist So, why hasn't that been removed in favor of Object.setPrototypeOf? Got a link to discussions, or a shorthand version?

The conversation keeps going and has one conclusion

@izs one-line fix: delete Object.prototype.__proto__; // put this in a module called "raygun-neutralizer" :)

Ha ha ha .. so funny the future of JavaScript comes with a foot-raygun included, don't you think? ^_^

V8 *Is* Based On An Object.setPrototypeOf Equivalent

Breaking news, uh? The internal ObjectSetProto function simply wraps exactly what I've proposed in es-discuss as Object.setPrototypeOf(target, proto).
In V8 internals represented as return %SetPrototype(this, obj);
So here the first thing: the engine of miracles needs such power but we, stupid JavaScripters, how do we dare!

A Poisoned __proto__

Not only this is the less consistent and the most ridiculous property ever introduced in Javascript, this is also intentionally poisoned as broken in Google engine.
These are a couple of quotes in my last attempt to make people reasonable in es-discuss, the first one is from Alex Russell, in this reply:

Assuming "this property" is __proto__, that ship sailed in V8 a long ago and there's zero chance of it ever being removed. It they want to remove it, they can simply fork V8 or ask for a build flag for it.

Not only this is alarming me, as V8 incapable of making changes if considered dangerous as security problems would be, but turned also out that Alex was wrong since today __proto__ is configurable so you can delete it..
.. and all you need to do, after forking, is to build putting a comment here.

set: desc.getSet(),// === ObjectSetProto ? ObjectPoisonProto
                   // : desc.getSet(),

That's it, after that you can have both __proto__ and a usable descriptor of it.
At this point, after a line change in V8 source code, all node.js could do to have a better environment is to do this during the sturtup:

(function(setPrototypeOf){
  if (setPrototypeOf in Object) return;
  var set = Object.getOwnPropertyDescriptor(
    Object.prototype, '__proto__'
  ).set;
  Object.defineProperty(
    Object,
    setPrototypeOf,
    {
      enumerable: false,
      configurable: true,
      value: function setPrototypeOf(target, proto) {
        set.call(target, proto);
        return target;
      }
    }
  );
  // TA-DAAAAAAA!!!
  delete Object.prototype.__proto__;
  // problem solved
}('setPrototypeOf'));

// example
var a = {},
    b = Object.setPrototypeOf({}, a);

a.isPrototypeOf(b); // true!

Above scenario does not look like so hard to implement, isn't it Brendan?
However, another concern was about all npm modules will be broken without considering node has versioning so that no, not a single npm will be broken and updated modules could easily swap to this new API maintaining the environment nice, still fast, and clean!

Moreover, the Object.setPrototypeOf equivalent, called ObjectSetProto and wrapping %SetPrototype(this, proto) in V8, is used to set all __proto__ properties, how cool is that?!

InstallGetterSetter($Object.prototype, "__proto__",
    ObjectGetProto, /* ARE YOU READY???? */ ObjectSetProto);

In few words, my proposal is naturally part of the language ... uh wait, this specific features has been commented as:

an added, _de novo_ API that no one wants, which is an ambient capability on Object, is bad and it won't happen

... it was here!
How would any developer want more power under her/his hands ... don't you dare thinking about it!

A Bit More Background

Brendan Eich excellently summarized with all links the story behind this property.
In few words, this property has been discussed and nobody wanted it.
They better preferred to quickly, dirty, spec it as configurable, at least, and as non present in Object.create(null) objects, so that finally some project could directly get rid of it and drop it via
delete Object.prototype.__proto__;
as mentioned before.
Moreover, this is another quote from Brendan the same es-discuss post:

Because @izs tweeted something you think Node is going to fork V8? Get real!

... So I Tried To Get Real ...

The change required to make that possible in V8 is a 10 seconds task, network push a part ... anyway ...

In Isaac slides you can read at page 26 that:

not developing a language removes a huge burden. Let TC-39 and V8 fight those battles for us!

So I didn't even bother him with this discussion ... I mean, he's doing the right thing: let other specialists solve problems for you so you can focus on something else .. right ?
The reality is that even if I send that patch to V8, they will not accept it, not even if Microsoft will agree as the right direction to promote a better standard!
The parody about this de-facto utopia is that all current IE browsers do not support __proto__.
IE is desperate to be part of the not finalized yet spec, and this is probably why the leaked version 11 shows __proto__ shenanigans in the wild .. and those specs are not final ...!

The Very Sad Result Of Thomas Fuchs Reaction

Since I've been fighting, blogging, and discussing this problem for months, and since many times they came back to me or others saying that:

It wasn't Node.js that drove that -- it was the "mobile (iOS WebKit first) web" that wanted __proto__ due to libraries such as Zepto.

So I've tried to reply at some point like:

I think zepto is using that to modify runtime NodeList results after querySelectorAll but in any case it was not me saying that __proto__ isn't used already...

The discussion goes on and on until I think one action is better than many words, right?

What Allen Wirfs-Brock Said

The good @awbjs, who writes ECMAScript Specifications, took kindly some of his time to reply to my post entitled Yet Another Reason To Drop __proto__.
This is his comment:

__proto__ wasn't TC39's mistake and everybody who participates on TC39 is aware of how terrible it is.
...
If you want to eliminate __proto__ you will have to eliminate its usage. Write a shim for Object.setPrototypeOf:
...
Then evangelize web developers like crazy to update all their existing deployed code to use this shim instead of directly using __proto__.
...
Good luck (seriously)

Challenge Accepted! ... so here the big drama ... that Allen "Good luck (seriously)" "benediction" transpiled in my mind as:

What the hack ... what does he mean with "goog luck (seriusly)", that JavaScript community is made by passive bigot developers that cannot change simple things?
Of course we are as good developers as those you can find in any other language ... let me demonstrate it describing the situation in a pull request commit with all tests greens and zero side effects!

The Community Reaction

Sure that once described the problem in Zepto.js repository, and I swear never a Zepto.js developer I know ever showed up in es-discuss or my blog, I've simply committed a patch that was tests approved and changing two lines of code promoting Object.setPrototypeOf instead of __proto__.
Long story short:

Here the Thomas rant, accusing me of trolling, after (kinda obviously) him not being aware of anything I've been written 'till now:

It's not about not agreeing with you. It's the form of how you imply or directly state that we're, I quote, "passive bigots" and that somehow __proto__ is insecure and "may" be removed and other weasel words that imply that we don't know what we're doing and you're a white knight to rescue us from ourselves. No, thank you. Please troll someone else.

Now, whatever Thomas thought was good to demonstrate with his reaction, which is simply, in my opinion, "the ball here is mine, nobody plays if I'm pissed off" ... since he decided to block me from the whole repository, all I could do is to write an answer in the same gist that is describing the current madness behind that property.
Really Thomas ... what can I say, congrats!

Thomas, Not Flex Box Again, Please!

So if IE will spec a document that's still a draft, and just to make for the broken web __proto__ can create, don't blame anyone if IE will implement that as broken as it is now almost spec'd!
Version 9 won't have it and neither 10, the current one in 2013!
If Zepto.js decides IE is not a target browser, this does not mean every library should decide the same!
Isn't one of our duty, as Web developers, to make the Web available to as many people as possible?
jQuery released today version 2 and IE9 and IE10 are supported, as easy as that .. or maybe that was the reason you were so nervous?
If Zepto wants to shoot in its foot saying __proto__ or nothing .. deal with that, you have less targets there and of course, you know that!
I mean, you better support IE9 and 10 in both Desktop and mobile for a while in any case, don't you?
So since this is the best moment to drop that mistake and go for a better, less obtrusive, pattern, why wouldn't you?

Update On The Repository

I am still blocked as if I've been trolling Zepto since ever but at least now Thomas rant is gone and there is a statement from Mislav Marohnić there I cannot comment but that makes sense for that library, except when it comes to talking about standards, since __proto__ is not even standard yet:

We generally don't pull contributions that don't improve anything. If, for instance, IE implemented the standard API but doesn't support __proto__, we would pull this. But we don't gain anything tangible with this change. We only believe in standards if they actually result in some benefit. We don't know what the "future of JS" is going to be, so we're making this neat little library that works in the present. When the future of JS arrives, I'm sure we'll adapt accordingly.

Revelation: Why Is Dropping Proto So Important To Me!!!

First of all, as I've said, is not just me ...
Secondly, __proto__ cannot be polyfilled while a modern Object.setPrototypeOf method could be much easier and consistently polyfilled across current browsers.
ES6 specifications aren't going out anny time soon so it's not too late to put a simple method out there able to make the future a bit brighter .. for node.js, for quickly updated browsers, for JavaScript, your favorite programming language.
You don't want too much power in a function? You shouldn't care since the language behind that function has it, so you are just thinking you should be limited, no matter how good or powerful or evil the function will be.
Thanks for reading until here, really appreciated!

Wednesday, April 17, 2013

How About KISS vs YAGNI ?

I know this might sound silly but I keep having fun writing stuff here
since I've switched to mark down text :P


### Is This A Natural Conflict ?
If you are wondering what I am talking about I have a very simple example:
the Linux world!  

In the specific case, file system operations!

```
# copy a file
cp file1.txt fle2.txt

# remove a file
rm file1.txt
```


### That's A Move File !
Yes, is really that simple! When you move a file you are sure that file has been copied,
it has the new name or the same, if in a different folder, and you can remove the first one.  
OK, OK, if you are a Windows user you might have experienced some lost file in the past
due accidents during the copy such "_not enough space_" I got it, but what if that's because you've been too KISS and not YAGNI?  


### The Software YAGNI Approach
If you can obtain that in a quite simple way, no need to complicate things around.


### The KISS Approach
If everything I need is more than an action, I am not going to like that.  
KISS is also used as concept behind APIs and final, production ready, products.


### The Reality
KISS, however, is probably the most difficult thing ever in programming languages ... 
guess why? There's no such thing as **simple** when it come to programming.  

Actually, the most user-friendly interfaces and interactions, are probably also
the most over engineered so ... you see?


### As Summary
I've no idea if these two approaches, both my favorites, could be confusing and in collision.  
What I know, is that while I was writing this post I've been thinking all the time how to represent
bloody acronyms in Markdown.  
  

It came out that basing my experience with KISS and YAGNI, the best solution I had in mind
was under everybody nose as **JSON**:
`{"KISS":"Keep It Simple, Stupid"}` and `{"YAGNI":"You Ain't Gonna Need It"}`  

Both have never been mentioned in the [Markdown famous post](http://daringfireball.net/projects/markdown/syntax), something I'd love to contribute updating it!

Monday, April 15, 2013

Can Deal With Markdown In RSS Readers ?

I've spent some time trying to solve the
[tinydown](https://github.com/WebReflection/tinydown#tinydown)
runtime blogspot parsing and this is the current status:

  1. desktop browsers are fine
  2. mobile browsers are now fine too
  3. textual browsers lynx like are wonderful now!
  4. browsers without CSS are just fine
  5. browsers without JS are kinda fine too
  6. browsers without CSS and JS are almost fine


### Your RSS Reader
Most likely, what you are experiencing is something similar to point 5 or,
in the worst case scenario, point 6 of above list.

Being markdown easy to read as any plain text or book
you are familiar with, can you cope with that for RSS readers?


### As Experiment
Please give you some times to see if this work before answering.

I realy don't want to piss off my followers so the last option would be
to revert all my changes done in blogger
(or eventually host my blog in my own space)

One thing I am doing different now, is to preserve a decent amount
of columns before I go into a new line so readers unable
to adopt a `white-space: pre-wrap;` like rendering for feeds
should not be that disturbed anymore ...

If this is going to work, I think everyone could be happy
about the fact not only you can blog on the cloud without a host,
but what you write can be compatible with emails and everything
that is not HTML enabled ... all plain text, as universal way to
write a human friendly formatted document.

What do you think? Thanks for your patience!

Sunday, April 14, 2013

Flight Mixins Are Awesome!

OK, OK, probably is just that I cannot wait to start writing stuff with [tinydown](https://github.com/WebReflection/tinydown#tinydown) but I tweeted about this after last #FlightNight and @angustweets demo ... so here what is behind [Flight](http://twitter.github.io/flight/) mixins choice.


### The Basics

JavaScript polymorphism is probably one of the best things you can find out there.

Not kidding, the flexibility that this language offers when it comes to context injection and runtime class definition is simply amazing, as simple, and amazing, is this idea:

```js
// most basic example
function enriched() {
  this.method = function () {
    // do stuff
  };
}
```

Most common books and online documents usually describe above example as a _constructor with privileged methods_.

Well, that's actually what you get if you `var obj = new enriched();` but that's just one story.
Flight uses a different story, offering alternative methods with better semantics but basically going down to:

```js
enriched.call(object);
```


### Mixins Baby!

Using above pattern we can enrich any sort of object with the extra benefit of having a private scope the moment we invoke once the function.
This gives us the opportunity to pass arguments or simply have some private, shared in case of a prototype, variable too.

```js
// with arguments and private variables
var Mixin = function Mixin(arg0, argN) {

  // private variables
  var scoped = {};

  // privileged methods
  this.method = function method() {
    return scoped;
  };

  // default properties or initialization
  this.prop = arg0 || 'default';
  this.other = argN;

};

// ========================================

// as Singleton
var singleton = new Mixin;
singleton.method(); // object
singleton.prop; // default
singleton.other; // undefined

// as prototype with defaults
function Class() {}
Mixin.call(Class.prototype, 'a', 'b');

var instance1 = new Class,
    instance2 = new Class;

instance1.method(); // object
instance2.method(); // same object

// same methods
instance1.method === instance2.method; // true

// and same object
instance1.method() === instance2.method(); // true

instance1.prop;  // a
instance1.other; // b
instance2.prop;  // a
instance2.other; // b
```

I have realized how powerful is this simply considering the same approach with prototypes rather than each objects, where methods are of course created per each invokation of the mixin, but that would be indeed absolutely meant and expected.

What I am saying, is that if you are worried about too many closures and functions generated per each mixin, and you believe your mixin does not need any initialization and methods can be used anywhere without needing a private scope, here all you can do to follow same pattern and save a bit of memory:

```js
var Mixin = function(){
  // created once and never again
  function method1(){}
  function method2(){}
  function methodN(){}
  return function () {
    this.method1 = method1;
    this.method2 = method2;
    this.methodN = methodN;
  };
}();
```

I guess that's it, right? But what if we need some sort of initialization per each mixin?

  
### Initializing A Mixing

There could be things we need to do to ensure the mixin will work as expected per each instance but if we want to coexist out there in the wild, we cannot name methods like `.init()` because of the name clashing if more than a mixin needs to be initialized ... are you following?

One possible solution that came into my mind is to prefix, with `init` the method, and use the mixin name as suffix.

```js
// defaults plus init
var Mixin = function Mixin(dflt0, dfltN) {

  // private variables
  var scoped = {};

  // privileged methods
  this.method = function method() {
    return scoped;
  };

  // avoid multiple mixins name clashing
  // prefix eventual initialization
  // with 'init' plus mixinname
  this.initMixin = function (arg0, argN) {
    this.prop = arg0 || dflt0 || 'default';
    this.other = argN || dfltN;
  };

};
```

If we follow this approach, we can initialize any mixin we want at any time, e.g.:

```js
// explicit initialization
function Class(arg0, argN) {
  this.initMixin(arg0, argN);
}
Mixin.call(Class.prototype, 'a', 'b');

var instance1 = new Class,
    instance2 = new Class('different');

instance1.prop;  // a
instance2.prop;  // different
instance1.other; // b
instance2.other; // b
```

Per each instance we can then enrich the constructor so that every mixin that needs to be initialized at that time can be simply call the non clashing method.


#### Some Bad Idea You might Have

Well, it is common in JS to think about `for/in` loops and stuff so that if we know a prefix we can automate tasks ... but in this case I strongly discourage this approach unless you are not 100% sure all mixins initializations support same signature.

```js
// *DONT* automatic mixin initialization
function Class() {
  for (var key in this) {
    if (key.slice(0, 4) === 'init') {
      this[key]();
      // or
      this[key].apply(this, arguments);
    }
  }
}
```

In few words, using above technique means coupling mixins with a specific, probably unknown in advance, class signature so it is strongly discouraged.

Sticking with an explicit mixin initialization is not only faster but able to create any sort of mixin signature.


### Events To The Rescue

As @kpk reminds me, [Flight is event based](https://twitter.com/kpk/status/323272363053551616) so there's also an easy way to do more after all mixins initialization: `this.after('initialize', fn);`


### As Summary

This is only one part of [Flight](http://twitter.github.io/flight/) where [**performance**](http://jsperf.com/mixin-fun/31) were strongly considered for all old and new browsers and this works.

In an era were many developers are looking for better classes this framework came out with such simple and powerful solution I can't believe I would like to have anything more than this for real apps!

Enjoy the Flight philosophy and embrace powerful simplicity any time you _A-HA_ it ;)

Saturday, April 13, 2013

tinydown test

OK ladies & gentlemen, time to test [tinydown](https://github.com/WebReflection/tinydown#tinydown) for real.

### What's New
Well, first of all there are [35 tests](http://webreflection.github.io/tinydown/test/) with nice and/or screwed input and an expected output to complete the library so that any improvement or change will not compromise what's already working.

The second thing is ... **I am using tinydown now**!

You can check the source page of this post and see that all it contains is markdown.

### What's Different
There at least two things different:

  * it supports more inside the image markup, such youtube and gists
  * it supports twitter handlers, like @WebReflection
  * even if so damn small, like less _than 2Kb_ minzipped, it supports nested blockquotes and lists

`inline code` is also available together with triple tick syntax and/or tab and spaces so that

    var code = 'can be be written multiline';
    function alCodeIsPreserved() {
      with(out) {
        alert('problems');
      }
    }

I also implemented only here the highlighter for js so

```js
var code = this.should();

code.look('gorgeous');
```

### What's Missing
I don't know yet, I think almost everything I need for blogging should be there.

The library is compatible with both _node.js_ and web browsers, of course, and if tests are green you should good to use it runtime in your blog too or any other place you think.

Last but not least, you can **test everything** you want in [this page](http://webreflection.github.io/tinydown/test/test.html live test) and eventually file bugs copying the generated link with your content so it will be straight forward to see what's broken, the why and the how.  
  
Have fun!

Thursday, April 11, 2013

Writing Markdown In Blogger

Update

Added tests and support for nested blocks and lists plus youtube video and gists instead of just images.
Here, have a look at tinydown, compatible with both node and web.
Something I've been thinking about since last year JS1K contest ... what if I could just write mark down on internet and let crawlers and bots do the math while I just write all I need to?

tinydown and CloudReflection

This is basically all it took to create a markdown blogger enabled service as CloudReflection is.
That's correct, if I edit that post the text I gonna deal with is this one:
Isn't a tiny markdown parser lovely ?
=====================================

A markdown is an _easy to read and quite easy to parse_ syntax, ideal for documents
that could be understood by human, and easily converted by machines.

You are reading markdown now!
-----------------------------
This blogpost is generated on the fly via the proposed script.  
Here the code **example** used for this page:

    this.onload = function () {
      document.body.innerHTML = tinydown(
        document.body.textContent
      );
    };

You can find a very nice guide about [how to markdown here](http://daringfireball.net/projects/markdown/syntax "markdown style guide").

### What is supported ?
  * headers with = or - notation
  * headers with # notation
  * blockquotes and nested blockquotes
  * ordered and unordered lists
  * images with optional alt ant title
  * inline links with arbitrary title
  * <em> via single asterisks/underscore, or double for <strong> tag
  * inline `code` via `` ` `` backtick

### What is not supported ? ###
  * paragraphs are missings
  * nested lists and nested markdown inside lists
  * links with references and/or id
  * raw html is not recognized, validated, parsed

> and just to demonstrate it works
> > this is a nested blockquote example :-)
> have a lovely day

- - -
© WebReflection
This is basically the same text I've used in the original demo page, except links and images are now finalyl supported.
That is going to look exactly the same way you look at it in the following iframe:

What Else On Blogger Side

So I had to include a couple of scripts:
  1. <script src='http://webreflection.github.io/tinydown/test/build/tinydown.js'/>
  2. <script src='http://webreflection.github.io/tinydown/test/build/onstuff.js'/>
While the first one is the actual tinydown parser, the second one is just some logic to parse the right content at the right time.
If you want to play with npm install tinydown parser consider that's just a function and is not as complet eas any other fully compatible markdown parsers ... it just gives me basically everything I need to write my technical posts on blogger ... can I ask anything more? I don't think so!
Bear in mind you should not use same scripts with github external repository file in your production code/blog ... just follow these direction, and stay tuned with the tiny down repository.