Sunday, October 9, 2011

Taking The Bat-Formula To The Next Level

When you wake up on Sunday morning with upside-down stomach and batcode in mind, you may realize it's time to rest a bit.

with (/*Bat*/Math) Array(16).join(
pow(/*JOK*/E/*R*/, cos, E/*vil*/)
) + "batman";

The output is the same produced by the original bat-formula:

'NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNbatman'

Have a nice Sunday.

A Better is_a Function for JS

In 2007 I have posted about get_class and is_a functions in JavaScript in order to simulate original PHP functions.

Well ... that was crap, since a much simpler and meaningful version of the is_a function can be easily summarized like this:

var is_a = function () {
function verify(what) {
// implicit objet representation
// the way to test primitives too
return this instanceof what;
}
return function is_a(who, what) {
// only undefined and null
// return always false
return who == null ?
false :
verify.call(who, what)
;
};
}();

... or even smaller with explicit cast ...

function is_a(who, what) {
// only undefined and null
// return always false
return who == null ?
false :
Object(who) instanceof what
;
}

An "even smaller" alternative via @kentaromiura

function is_a(who, what) {
return who != null && Object(who) instanceof what;
}


Here a usage example:

alert([
is_a(false, Boolean), // true
is_a("", String), // true
is_a(123, Number), // true
is_a(/r/, RegExp), // true
is_a([], Array), // true
is_a(null, Object), // false
is_a(undefined, Object) // false
]);

As twitted few minutes ago, an alternative would be to pollute the Object.prototype:

Object.defineProperty(Object.prototype, "is_a", {
value: function (constructor) {
return this instanceof constructor;
}
});

// (123).is_a(Number); // true

However, this way would not scale with null and undefined so that per each test we need to check them and this is boring.
Finally, I would not worry about cross frame variables since via postMessage everything has to be serialized and unserialized.

Thursday, October 6, 2011

implicit require in node.js

playing with Harmony Proxy I came out with a simple snippet:


The aim of above snippet is to forget the usage of require ... here some example:

module.sys.puts("Hello implicit require");

var fs = module.fs;
fs.stat( ... );

It's compatible with nested namespaces too and if there are non JS chars in the middle ... well:
var Proxy = module["node-proxy"];