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

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.

Saturday, March 30, 2013

Yet Another Reason To Drop __proto__

I know it might sound boring but I really want to put everything down and laugh, or cry harder, the day TC39 will realize __proto__ was one of the most terrible mistakes.

A Simple Dictionary Attack

ES6 says that Object.create(null) should not be affected anyhow from Object.prototype.
I've already mentioned this in the 5 Reasons You Should Avoid __proto__ post but I forgot to include an example.
You can test all this code with Chrome Canary or Firefox/Nightly and the most basic thing you need to know is this:
var n = Object.create(null);
n.__proto__ = {};

for (var k in n) console.log(k); // __proto__ !!!
Object.keys(n); // ["__proto__"] !!!
Got it? So, __proto__ is enumerable in some browser, is not in some other but it will be in all future browsers. Let's go on with examples ...
// store values grouped by same key
function hanldeList(key, value) {
  if (!(key in n)) {
    n[key] = [];
  }
  n[key].push(value);
}
// the Dictionary as it is in ES6
var n = Object.create(null);
Above code simply does not need to be aware of any problems except in older environment that won't work as expected. If the key is __proto__ instead of storing the value there will be most likely an error or the object will inherit from an empty array the moment n[key] = [] will be executed.
In few words, I believe you don't want to fear security and logic problems every single time you set a property to a generic object ... am I correct?
Now imagine some library such underscore.js, has the most common and generic way to create an object from another one, copying properties ...
function copy(obj) {
  var result = {}, key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      result[key] = obj[key];
    }
  }
  return result;
}

// or if you want ... 
function extend(a, b) {
  for (var key in b) {
    if (b.hasOwnProperty(key)) {
      a[key] = b[key];
    }
  }
  return a;
}
Now guess what happens if you would like to copy or extend that list we had before, where __proto__ will be own property for the n variable and the loop is not checking the key as it should ... the object a, or the new one, will automatically extend an Array and break completely its own expected behaviors ^_^
This is nothing an explicit Object.setPrototypeOf() could cause ... moreover...

Real World Performance Impact

Every utility such lo-dash or underscore should now do this kind of check per each loop if these would like to be considered safe:
function copy(obj) {
  var result = {}, key;
  for (key in obj) {
    if (
      obj.hasOwnProperty(key) &&
      key !== '__proto__'
    ) {
      result[key] = obj[key];
    }
  }
  return result;
}
Now try to investigate in your real-world daily code how many times you change __proto__ compared with how many times you loop over properties ... I give you a test case to compare performance and remember: mobile matters!

Really Hard To Debug

Being a special property in the Object.prototype and not just a function you could wrap and keep under control, in a new scenario where any object could be instanceof anything at any time, the inability to intercept __proto__ calls and changes before it happens will be a painful experience in terms of debugging ... what was that instance before? Most likely, you'll never know ^_^
It must be said some engine makes that descriptor.setter reusable but this is not the case of current V8, as example, neither the case for all mobile browsers out there today.

A Stubborn Decision

What's driving me crazy about this property and all problems it brings, is that regardless there is a possible "speccable" Object.setPrototypeOf() alternative that would not suffer from anything I've described in all these posts, and just as reminder there is already a spec'd and widely available Object.getPrototypeOf() in ES5, TC39 will go on and make the problem a standardized one ^_^
I haven't been able to reason against them regardless examples and reasons ... but you could have fun trying too before it's too late!

Friday, March 29, 2013

Simulating ES6 Symbols In ES5

Symbols, previously known as Names, are a new way to add real private properties to a generic object.
// basic Symbol example
var BehindTheScene = (function(){
  var symbol = new Symbol;

  function BehindTheScene(){
    this[symbol] = {};
  }

  BehindTheScene.prototype.get = function(k) {
    return this[symbol][k];
  };

  BehindTheScene.prototype.set = function(k, v) {
    return this[symbol][k] = v;
  };

  return BehindTheScene;

}());

var obj = new BehindTheScene;

obj.set('key', 123);

obj.key; // undefined
obj.get('key'); // 123
In few words symbol makes possible to attach properties directly without passing through a WeakMap. A similar behavior could be obtained indeed via WeakMaps:
// similar WeakMap example
var BehindTheScene = (function(){
  var wm = new WeakMap;

  function BehindTheScene(){
    wm.set(this, {});
  }

  BehindTheScene.prototype.get = function(k) {
    return wm.get(this)[k];
  };

  BehindTheScene.prototype.set = function(k, v) {
    return wm.get(this)[k] = v;
  };

  return BehindTheScene;

}());

var obj = new BehindTheScene;

obj.set('key', 123);

obj.key; // undefined
obj.get('key'); // 123

Why Symbols

To be honest I am not sure but these somehow bring some magic to the object rather than wrapping magic around it, as it is for the WeakMap example, so at least performance should be better ... right? Well, the current shim VS shim says that indexOf() is faster than an implicit toString(): check this test out by yourself ;)
In any case it looks like private symbols will be a better way to go than WeakMap when all we would like to have is a private property. Symbols can be used as Enums too, being unique as any other object is.

Simulating Symbols In Current ES5 JavaScript

As easy as this:
var Symbol;
if (!Symbol) {
  Symbol = (function(Object){

    // (C) WebReflection Mit Style License

    var ObjectPrototype = Object.prototype,
        defineProperty = Object.defineProperty,
        prefix = '__simbol' + Math.random() + '__',
        id = 0;

    function get(){/*avoid set w/out get prob*/}

    function Symbol() {
      var __symbol__ = prefix + id++;
      defineProperty(
        ObjectPrototype,
        this._ = __symbol__,
        {
          enumerable: false,
          configurable: false,
          get: get, // undefined
          set: function (value) {
            defineProperty(this, __symbol__, {
              enumerable: false,
              configurable: true,
              writable: true,
              value: value
            });
          }
        }
      );
    }

    defineProperty(Symbol.prototype, 'toString', {
      enumerable: false,
      configurable: false,
      writable: false,
      value: function toString() {
        return this._;
      }
    });

    return Symbol;

  }(Object));
}
A very basic example here:
var sym = new Symbol;
var o = {};
o[sym]; // undefined

o[sym] = 123;
console.log(o[sym]); // 123
for (var k in o) {
  console.log(k); // nothing at all
  // there is nothing to for/in
}
delete o[sym]; // true
Of course, you can try also the very first example, the one with a shared, private, symbol variable, that will simply work as expected :)
Bear in mind, regardless being a hack, this script does not actually cause any problem to any other script or library you are using today but it needs ES5 compatible browsers such all mobiles plus all desktops and IE9 or greater.

Tuesday, March 26, 2013

5 Reasons You Should Avoid __proto__

Update: when you've done with this post, there's even more in comments and the newer one: Yet Another Reason To Drop __proto__
Too many discussions without real outcome about __proto__ magic evilness or feature. It's time to understand why using it is, today, a bad idea.

__proto__ Is NOT Standard (yet)

TC39 refused to standardize this property because of the amount of problems it brings. Apparently will be part of ES6 but is not there yet.
__proto__ is a silent, non spec'd, agreement. What's the problem? Keep reading ;)

__proto__ Could NOT Be There

The silent non standard agreement sees __proto__ as configurable property of the Object.prototype.
As example, try this in some environment:
(this.alert || console.warn)(
  delete Object.prototype.__proto__
); // false or true ?
The outcome is migrating from false to true. As example, current Chrome has a non configurable descriptor, while Canary has a configurable one. Same is for latest node.js, Firefox, and who know who else.
Having a property configurable means you cannot trust it's going to work because anyone could have decided to remove it ... why ...

__proto__ Makes null Objects Unpredictables

Theoretically, this is all you need to create one or more objects that inherits from null
var Dict = Object.create.bind(Object, null);

var dictionary = Dict();
dictionary[property] = 1;
if (otherProperty in dictionary) {
  // do stuff
}
// or
if (dictionary[someOtherThing]) {
  // do stuff
}
We cannot trust, as example in Chrome, that any property can be set there because if for some reason the property name is __proto__, that object inheriting null will completely be unusable/screwed.
Using hasOwnPropertyDescriptor() is not even an option since objects that inherit from null do not inherit these methods from Object.prototype.
The extra silent agreement here is that Object.create(null) should return objects that are not affected anyhow by any property from Object.prototype and __proto__ ain't any exception!

__proto__ Is NOT Secure

Since any bloody object could be modified directly or deeply anywhere in the middle of its prototypal chain, you can consider all your instances somehow exposed to any sort of attack.
Bad news is: you cannot redefine __proto__ to prevent this, at least you cannot in current version of Chrome and mobile browsers:
function ProtoSafe() {}
Object.defineProperty(
  ProtoSafe.prototype,
  '__proto__',
  {
    get: function () {
      return ProtoSafe.prototype;
    },
    set: function () {
      throw 'immutable';
    }
  }
);
Error: cannot redefine property __proto__

__proto__ Influences Your Logic

This is last point but actually still important. In ES3 it has never been possible to redefine inheritance over an already created instance and this has never been a real problem.
Polymorphism has always been possible through mixins and borrowed methods but again, no way an object could suddenly be any sort of instance with such lightweight casting unable to ensure any desired behavior.
What I mean, is that using [].slice.call(arguments) has a meaning: if there is a length in the used object, create an array with indexes filled from 0 to that length - 1.
This is different from generic.__proto__ = Array.prototype; because the length could be missing and the resulted object behavior be unexpected, broken, or again unpredictable.

Still A Cheap Way To Cast

This is the only advantage and the reason some library adopted __proto__ without even thinking about it: performance boost, compared to a whole slice, are a win, and specially in mobile and DOM libraries where results are always threat as ArrayLike objects.

Object.setPrototypeOf(object, proto) To The Rescue!

In ES5 all Object things are managed through the Object constructor so why not having a method in charge of the __proto__ behavior, since Object.getPrototypeOf(object) is already available?
Here some advantage:
  1. no way a property can destroy an object, the obj[propName] check against propName !== '__proto__' won't be needed anymore: performance!
  2. cheap casting still available so not a performance issue
  3. standardizing Object.setPrototypeOf(object, proto) can bring new possibilities such Object.freezePrototype(object) in order to ensure immutable inheritance when and if needed

A Cheaper Example

If you want to ensure TC39 will ever consider to drop this property in favor of better methods in the Object, here what you should stick in your library that is using proto:
var setPrototypeOf = Object.setPrototypeOf || function(o, p){
  o.__proto__ = p;
  return o;
};
It's cheap and performance, again, are as good as before!

Sunday, March 17, 2013

Some Repo News

Well, I don't always post about updates, changes, or new repos here, so here a quick and dirty post on things I've been tweaking, creating, or fixing, recently.

DOM4

This 100% test covered polyfill is awesome! Combined with some basic utility makes DOM manipulation life really easy. As example, this is how you can shuffle last to first one a list of li:
var li = document.querySelectorAll('ul.shuffle li');
li[0].before(li[li.length - 1]);

// or even better!
var ul = li[0].parentNode;
ul.prepend(ul.lastChild);
Pretty cool stuff from W3C!

experimental.js

The most compact and easy way to retrieve experimental features, or standardized, now supports CSS prefixes too.
var JSkey = experimental(
  window,
  'requestAnimationFrame'
  // optionally explicit, 'js'
);
// JSkey is the string
// webkitRequestAnimationFrame
// mozRequestAnimationFrame
// others too or
// requestAnimationFrame

// forcing JS assignment
if (!experimental(
  window,
  'requestAnimationFrame',
  true // force assignment
)) {
  window.requestAnimationFrame = function(cb){
    return setTimeout(cb);
  };
}

// now available in all browsers
requestAnimationFrame(daFunction);


var CSSkey = experimental(
  document.documentElement.style,
  'transform',
  'css'
);
// -webkit-transform
// -moz-transform
// or
// transform

require-updated module

Have you ever needed a module that updates automatically as soon as it's edited in node.js world? This module is meant to provide the most recent version of a module, of course if this is required in the wild rather than once at the top of the JS program.

polpetta

Some minor clean up and some big plan ahead, makes it the very first fully node.js web server with simplified configurations, as it is now, but extended to stream, gzip, and caching with ETags and all other common techniques to avoid the usage of a web server on top of it at all.
No idea how much this will take but I am willing to provide some good shit by the time node v1 is out, after next, 0.12, release.
If you don't know what is polpetta yet, considered it's the easiest way to have CGI like behavior in node.js in any folder and that it has been tested in all possible environments with excellent performance, even Raspberry PI, pcDuino, RK3066 modules, as well as Amazon server (not in production, I need those adds-on first).
This update is more about telling you that things are being improved and the project is everything but dead and the require-updated module has been created for polpetta indeed ;-)

gitstrap environment

While many keep struggling with node updates and the inability to run grunt, this or that dependency, gitstrap keeps being slightly improved making my git flow every day easier. Travis, wru tests, a proper Makefile, easy customization, I know I should probably spend a bit more time documenting or describing various "how-to" but I believe if you know very basics about bash and make, you don't need much from me there ;)

redefine.js

Not only a simplified, more secure, and battle-tested utility for ES5 engines (node.js, Rhino, others) and browsers (all mobile plus all desktops but IE8), now a simplified way to create Classes too.
Bringing the most useful part from the poo.js experiment, redefine.js now supports extend, to simplify inheritance in a semantic way, mixin as it will be in ES6, statics for constructors properties and public methods, and all other redefine powerful features like lazy property assignment, defaults for descriptors, and all other things needed for a Class based env, when and if needed!

CircularJSON Update

With support for non resolved paths when the extra flag is passed through .stringify(data[, receiver[, space[, DO_NOT_RESOLVE]]]).
The result will be similar to other parsers where the circular reference will have simply the word [Circular] in it.

You are welcome :) and see you soon!

Thursday, March 14, 2013

Solving Cycles, Recursions, And Circulars References In JSON

CircularJSON is my next level take on @getify thoughts about recursive-safe JSON.stringify() operation, going further than what @izs proposed with his json-stringify-safe module which aim, and purpose, can be summarized in his reply:
This module is useful for the use case I'm using it for. If it's not your cup of tea, well, GOOD NEWS! There are a lot of cups with a lot of different flavors of tea in them.
Thanks man, what you probably don't know is that actually, there are no concrete, safe, performant, solutions to that problem ... oh well, now there is one!

CircularJSON

My fully tested, 650 bytes, portable and cross platform solution, is based on same isaacz logic: the usage of JSON.stringify(data, receiver)
In few words, if you consider safe the native JSON, you can consider safe CircularJSON too in both serialization and deserialization.
Despite what you might think about recursive serialization, there's no magic behind and all tests can prove that CircularJSON is simply safe and working as you expect.

How Can Be That Safe

THe logic behind is based on native JSON behavior where the receiver and the reviver functions are all CircularJSON uses in order to work.
For the end user, same JSON API is preserved and it works as expected so nothing is different, except circular references are recreated during parse operation.
Once again, not a rewritten parser, neither a RegExp based solution, CircularJSON is the simplest solution to the most common circular, recursion, repeated object, problem.

How About Performance

This is tricky, and you can test performance via node test/benchmark.js and compare results in your machines and with your node version.
Generally speaking, performance is about twice as slow as regular JSON but only with never repeated data.
That's correct, as soon as there are repeated objects in the serialization and deserialization process, CircularJSON goes faster until being faster than JSON when there are more repeated objects in the stream.
I am obviously excluding cycles and circular references from the game since we all know JSON will simply fail, don't we?

Why Solving Circular References

First of all, because we are developers. If there are circular references it probably means we needed them, right? As summary, in my opinion, any attempt to get rid of circular references because of serialization is a failure for the simple fact that once deserialized, we canot have that reference back anymore.
THere could be cases we need circular references and as PHP, as example, solved them since ever through serialize() and unserialize() function, we might want to do the same via JavaScript: why not?!

Do Not Mix Shit!

While @izs thinks I am a moron noob, Kyle insinuated something could go wrong ... well, GOOD NEWS IS, they are both wrong as long as you don't use CircularJSON.parse() with data that has been encoded with JSON.stringify() and of course, the same is valid the other way round: do not .parse() via JSON what has been encoded via CircularJSON ... it's like using JSON to decode PHP serialized strings or vice-versa ... you know what I mean?

Welcome To Other Languages

As the fact it has been implemented in multiple programming languages helped JSONH to be that successful, and before, of course, JSON protocol itself, once many other programming languages in both client and server will be able to be compatible with circular references this project could be more widely adopted, specially to those that do not use node.js as server side solution.
Long story short, you are welcome, and thank you in advance, for any other language implementation you might want to push in this repository. Enjoy!

Monday, March 04, 2013

Breaking Array Extras

Every now and then somebody comes out with this problem:
How do I stop an iteration such forEach() ?
Well, there are at least a couple of ways to do that ...

Dropping The Length

The first tacky way to stop executing a function is to drop the length of the array. Every extra receives the initial ArrayLike object as third parameter so a function like this should be safe enough:
function forEachAndBreak(value, i, arr) {
  if (someCondition(value)) {
    arr.length = 0;
  }
}

someArray.forEach(forEachAndBreak);
Bear in mind, this will affect the initial array too so if this is not desired, a copy is needed:
someArray.slice().forEach(forEachAndBreak);

Cons: Still Looping

Even if this trick works as expected, there is something we don't see behind the scene: the loop is still going on. If you ever wrote some array polyfill, you might have heard that the for loop should verify that i in arr is true, before invoking the function or handling the value at that index since the Array might be a sparse one, where some index might be missing. The same happens with native arrays, you might try this and be stuck for a while: Array(0xFFFFFF).forEach(alert). It does not matter if that alert will never be called, the engine is looping through the whole length and verifying each index.

Using Some

This is the most common way to prevent the problem.
[1,2,3].some(function (value, i, arr) {
  alert(i);
  if (value === 2) {
    return true;
  }
});
Above will alert only 0 and 1 and the loop will be terminated as soon as true is returned. To quickly test this, let's use again that horrible, gigantic, Array ...
var a = Array(0xFFFFFF);
a[1] = 2;
a.some(function(v){if(v === 2) return true});
You'll notice that this time the return is immediate, there's no reason to wait after the first result.
In few words, Array#some() is way better than forEach() in all those situations where we would like to break the loop at any time: we just return true when we want to, no need to return anything in all other cases.

Array#every() Is NOT The Opposite Same

THe thing you might confuse about every is that you always need to return something while this is not the some() case. As we have seen, we return only when/if we want to break.

Finding The Index Or The Value: The Outer Scope Way

Another common pattern is to use this approach to actually find the index, something Array#indexOf() cannot achieve when the condition is more complicated than just a simple === comparison. Using an external variable can help here:
var index;
if (array.some(function (value, i) {
  if (complicatedCheckAgainst(value)) {
    index = i;
    return true;
  }
})) {
  doComplicatedStuffWith(array[index]);
}
Analogue situation with the value, so that we can directly retrieve what we are looking for if needed. However, this is kinda less common/used pattern since with the index we might splice or do more operations than just getting the value;

Finding The Index: The RegExp Way

This is quite tacky but fast enough and suitable when the extra argument is not used: I am talking about the context.
var index = array.some(function (value, i) {
  if (complicatedCheckAgainst(value)) {
    return this.test(i);
  }
}, /\d+/) && +RegExp['$&'];
if (index !== false) {
  doComplicatedStuffWith(array[index]);
}
Above pattern can be handy for inline operations:
[].some.call(body.childNodes,flagIt,reNum) !== false &&
(body.childNodes[RegExp['$&']].flagged = true);
Whenever it makes sense or not, we can reuse that function and that reNum in different situations and inline, without needing to create an outer variable. Latter point is indeed the main advantage, reusability without knowing the outer scope. This could be achieved creating something similar via a closure, but that would be probably boring...

Array#findIndex

It looks like TC39 will talk about a method ilke this too, so here what I believe would be a draft candidate:
(function(AP){
AP.findIndex || (
  AP.findIndex = function(fn, self) {
    var $i = -1;
    AP.some.call(this, function(v, i, a) {
      if (fn.call(this, v, i, a)) {
        $i = i;
        return true;
      }
    }, self);
    return $i;
  };
);
}(Array.prototype));
Enjoy!