coffee-factory
Version:
Javascript class Factory generator implemented in Coffeescript.
46 lines (45 loc) • 1.57 kB
JavaScript
// Generated by CoffeeScript 2.0.0-beta7
void function () {
var Factory;
module.exports = Factory = function () {
Factory.prototype.usable = [];
Factory.prototype.args = [];
function Factory(param$, param$1, args) {
args = 3 <= arguments.length ? [].slice.call(arguments, 2) : [];
this.klass = param$;
if (null == param$1)
param$1 = 0;
this.maxReuse = param$1;
if (typeof this.klass !== 'function')
throw new TypeError('' + this.klass + ' is not instantiable with `new`');
if (this.maxReuse < 0)
this.maxReuse = 0;
this.setConstructorArgs.apply(this, args);
}
Factory.prototype.setConstructorArgs = function (args) {
args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
return this.args = [null].concat(args);
};
Factory.prototype.get = function () {
var obj;
if (this.usable.length > 0) {
obj = this.usable.shift();
} else {
obj = new (this.klass.bind.apply(this.klass, this.args));
}
if (typeof this.klass.prototype.initialize === 'function')
this.klass.prototype.initialize.apply(obj, arguments);
return obj;
};
Factory.prototype.put = function (obj) {
if (!(obj instanceof this.klass))
throw new TypeError('Factory can only store an instance of type ' + this.klass);
if (this.maxReuse > 0) {
if (this.usable.length >= this.maxReuse)
this.usable.shift();
this.usable.push(obj);
}
};
return Factory;
}();
}.call(this);