-
-
Save GCheung55/247725 to your computer and use it in GitHub Desktop.
Collection Native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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