Skip to content

Instantly share code, notes, and snippets.

@GCheung55
Forked from keeto/Collection.js
Created December 2, 2009 23:37
Show Gist options
  • Save GCheung55/247725 to your computer and use it in GitHub Desktop.
Save GCheung55/247725 to your computer and use it in GitHub Desktop.
Collection Native
function Collection(list){
this.list = $splat(list || []);
this.length = this.list.length;
};
new Native({name: 'Collection', initialize: Collection, generics: false});
(function() {
// Some browsers don't iterate over natives, so brute force is required.
var natives = ["indexOf", "join", "lastIndexOf", "pop", "push", "reverse", "shift", "slice", "sort", "splice", "unshift"];
natives.each(function(item){
Collection.implement(item, function(){
this.fireEvent(item, Array.prototype.slice.call(arguments));
var results = Array.prototype[item].apply(this.list, arguments);
if (({pop:1, push:1, shift:1, unshift:1})[item]) this.length = this.list.length;
return results instanceof Array ? new Collection(results) : results;
});
});
// Now for extensions..
for (var i in Array.prototype){
if (Array.prototype[i] instanceof Function) (function(item){
Collection.implement(i, function(){
this.fireEvent(item, Array.prototype.slice.call(arguments));
var results = Array.prototype[item].apply(this.list, arguments);
return results instanceof Array ? new Collection(results) : results;
});
})(i);
}
Collection.implement($extend({
toString: function(){
return this.list.toString();
},
valueOf: function(){
return this.list.valueOf();
},
concat: function(){
var args = Array.prototype.slice.call(arguments);
this.fireEvent('concat', args);
args = args.map(function(i){ return i instanceof Collection ? i.list : i; });
var results = Array.prototype.concat.apply(this.list, args);
return results instanceof Array ? new Collection(results) : results;
}
}, new Events));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment