Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Created July 17, 2010 16:45
Show Gist options
  • Save tbranyen/479638 to your computer and use it in GitHub Desktop.
Save tbranyen/479638 to your computer and use it in GitHub Desktop.
// Collection iterator
self.each = function(_collection, _callback) {
var method, index, item, collection, keys, wrapper,
index_r = "i",
item_r = "_collection[i]",
collection_r = "_collection";
// Normal collection
if(_collection.length > 0 || _collection instanceof Array) {
method = true;
wrapper = "for(var i=0, len=_collection.length; i<len; i++) {";
}
// Object collection iterate using Object.keys
if("keys" in Object && !method) {
keys = Object.keys(_collection);
if(keys.length > 0) {
index_r = "keys[i]";
item_r = "_collection[keys[i]]";
wrapper = "for(var i=0, len=keys.length; i<len; i++) {";
method = true;
}
else {
method = false;
}
}
// Object collection (iterate over properties)
if(!method) {
wrapper = "for(var i in _collection) { if(!_collection.hasOwnProperty(i)) continue; ";
}
// Get function source
var callback = _callback.toString(),
// Isolate the function body and the parameters
body = callback.substring( callback.indexOf("{")+1, callback.lastIndexOf("}") ),
params = callback.substring( callback.indexOf("(")+1, callback.indexOf(")", callback.indexOf("(")+1) ).split(",");
// Map the index parameter
if(typeof params[0] === "string" && params[0].length) {
index = params[0].replace(whitespace, '');
body = body.replace(new RegExp("\\b"+ index +"\\b","g"), index_r);
// Map the item parameter
if(typeof params[1] === "string") {
item = params[1].replace(whitespace, '');
body = body.replace(new RegExp("\\b"+ item +"\\b","g"), item_r);
// Map the collection parameter
if(typeof params[2] === "string") {
collection = params[2].replace(whitespace, '');
body = body.replace(new RegExp("\\b"+ collection +"\\b","g"), collection_r);
}
}
}
// Map all context instances and returns
body = body.replace(replace_this, item_r);
body = body.replace(replace_return, "break");
// Create the loop and execute it
eval(wrapper + body +'}');
return _collection;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment