Created
July 25, 2011 05:25
-
-
Save 1Marc/1103606 to your computer and use it in GitHub Desktop.
"But $.each is slow!" ..use fn arrEach and objEach then!!
This file contains hidden or 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
// arrEach and objEach plugins | |
// code under MIT license by Marc Grabanski http://marcgrabanski.com | |
// jsperf tests: http://jsperf.com/each-vs-fn-arreach-and-objeach/2 | |
$.arrEach = function(arr, cb){ | |
for (var i = 0, item; item = arr[i]; ++i) { | |
cb.apply(item, [i, item]); | |
} | |
return arr; | |
} | |
$.fn.arrEach = function(cb){ | |
return $.arrEach(this, cb); | |
} | |
// examples using array each | |
$.arrEach(["foo", "bar"], function(i, item){ | |
console.log(i, item); | |
}); | |
$(["foo", "bar"]).arrEach(function(i, item){ | |
console.log(i, item); | |
}); | |
// JSPerf results show mixed results of faster/slower for objEach, but huge gains for $.arrEach. | |
// This is why you test everything folks!! | |
$.objEach = function(obj, cb){ | |
for (var i in obj) { | |
cb.apply(obj[i], [i, obj[i]]); | |
} | |
return obj; | |
} | |
$.fn.objEach = function(cb){ | |
return $.objEach(this, cb); | |
} | |
// examples using object each | |
$.objEach({"foo":"bar", "baz":"bla"}, function(i, item){ | |
console.log(i, item); | |
}); | |
$({"foo":"bar", "baz":"bla"}).objEach(function(i, item){ | |
console.log(i, item); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:D anytime dude