Skip to content

Instantly share code, notes, and snippets.

@willywongi
Created March 29, 2011 13:36
Show Gist options
  • Save willywongi/892364 to your computer and use it in GitHub Desktop.
Save willywongi/892364 to your computer and use it in GitHub Desktop.
arbitrary arguments length object constructor, in Javascript
function CONAN(cls) {
/* Arbitrary Number of Arguments Object Constructor,
ANAOC
but everyone calls him
CONAN
CONAN takes a Object Constructor and adds a static method named "build", whose only
argument is an array that get passed to the Constructor with an apply.
*/
var _helper = function(s) {
cls.apply(this, s);
};
_helper.prototype = cls.prototype;
cls.build = function(s) {
return new _helper(s);
};
};
/* Super is just a simple class that takes a reducing function (I defined SUM and MUL) and
an arbitrary number of arguments.
It has a "run" method that applies the reducing function; if one of the operand is an instance
of the Super class, it 'run's it.
eg.:
>>> a = new Super(SUM, 1, 2, 3);
>>> a.run();
>>> 6
>>> b = new Super(MUL, 2, a);
>>> b.run();
>>> 12
If you want to build Super instances while giving the constructor an arbitrary number of arguments,
you can let Conan help you:
>>> CONAN(Super);
>>> c = Super.build([SUM, 1, 2, 3, 4])
It adds a static method to your class that takes an Array and uses it content as the arguments
for the class constructor.
*/
var SUM = function(a, b) { return a + b; },
MUL = function(a, b) { return a * b; },
Super = function(op) {
this.op = op;
this._ops = Array.slice(arguments, 1);
};
Super.prototype.NAME = 'Super';
Super.prototype.get = function(i) {
if (i < this._ops.length) {
var op = this._ops[i]
return (op instanceof Super) ? op.run() : op;
}
};
Super.prototype.run = function() {
for (var r = this.get(0), i = 1, j = this._ops.length; i<j; i++) {
r = this.op(r, this.get(i));
}
return r;
};
CONAN(Super);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment