Created
January 6, 2012 04:39
-
-
Save afahy/1569010 to your computer and use it in GitHub Desktop.
Simple each( obj | array ) function
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
// each( collection { obj || array }, callback, [ context ] ) | |
// iterates over a collection, runs callback with either collection or optional context as value of 'this' | |
// | |
// callback sent the following arguments: | |
// * current item value | |
// * index or key | |
// * collection | |
( function( global ) { | |
function isObject( obj ) { | |
return Object.prototype.toString.call( obj ) === '[object Object]'; | |
} | |
function each( obj, callback, context ) { | |
var i = -1; | |
if ( isObject( obj ) ) { | |
for ( key in obj ) { | |
if ( obj.hasOwnProperty( key ) ) { | |
current = obj[key]; | |
if ( callback.call( context || obj, current, key, obj ) === false ) { break; } | |
} | |
} | |
} | |
else { | |
try { | |
for ( ; obj[++i]; ) { | |
current = obj[i]; | |
if ( callback.call( context || obj, current, i, obj ) === false ) { break; } | |
} | |
} | |
catch(e) { | |
throw new Error('Unable to iterate over ' + obj + ' ' + e.message ); | |
} | |
} | |
} | |
global.each = each; | |
// pass-in eg library.util etc instead of this if not desired in global namespace | |
}( this ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment