Skip to content

Instantly share code, notes, and snippets.

@michd
Created October 28, 2012 12:41
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save michd/3968505 to your computer and use it in GitHub Desktop.
JavaScript forEach Object, Array and String
(function () {
"use strict";
/**
* Iterate over an Object, Array of String with a given callBack function
*
* @param {Object|Array|String} collection
* @param {Function} callBack
* @return {Null}
*/
function forEach(collection, callBack) {
var
i = 0, // Array and string iteration
iMax = 0, // Collection length storage for loop initialisation
key = '', // Object iteration
collectionType = '';
// Verify that callBack is a function
if (typeof callBack !== 'function') {
throw new TypeError("forEach: callBack should be function, " + typeof callBack + "given.");
}
// Find out whether collection is array, string or object
switch (Object.prototype.toString.call(collection)) {
case "[object Array]":
collectionType = 'array';
break;
case "[object Object]":
collectionType = 'object';
break;
case "[object String]":
collectionType = 'string';
break;
default:
collectionType = Object.prototype.toString.call(collection);
throw new TypeError("forEach: collection should be array, object or string, " + collectionType + " given.");
}
switch (collectionType) {
case "array":
for (i = 0, iMax = collection.length; i < iMax; i += 1) {
callBack(collection[i], i);
}
break;
case "string":
for (i = 0, iMax = collection.length; i < iMax; i += 1) {
callBack(collection.charAt(i), i);
}
break;
case "object":
for (key in collection) {
// Omit prototype chain properties and methods
if (collection.hasOwnProperty(key)) {
callBack(collection[key], key);
}
}
break;
default:
throw new Error("Continuity error in forEach, this should not be possible.");
}
return null;
}
//Example uses
// Array example
forEach(["a", "b", "c"], function (value, index) {
console.log(index + ": " + value);
});
// Object example
forEach({"foo": "bar", "barfoo": "foobar"}, function (value, key) {
console.log(key + ": " + value);
});
// String example
forEach("Hello, world!", function (character, index) {
console.log(index + ": " + character);
});
}());
@michd
Copy link
Author

michd commented Apr 8, 2013

Note: This is old and probably shouldn't be used. Refer to several established libraries for solid implementations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment