forEach function (for array, objects and strings)

Function you pass a collection and a callBack function that takes index and value parameters. Arrays, Strings and Objects are supported.

by mich

JavaScript

function forEach(collection, callBack) {
    var 
        i = 0, //array/string iteration
        iMax = 0, //collection length storage for loop init
        key = '', //key storage for objects
        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": //intended fallthrough
        case "string":
            for (i = 0, iMax = collection.length; i < iMax; i+= 1) {
                callBack(i, collection[i]);
            }
            break;
            
        case "object":
            for (key in collection) {
                if (collection.hasOwnProperty(key)) {
                    callBack(key, collection[key]);
                }
            }
            break;
            
        default:
            throw new Error("Continuity error in forEach, this should not be possible.");
            break;
            
    }
    
    return null;   
}


forEach(iterateArray, function(index, value) {
    console.log(index.toString() + ": " + value.toString());
    a.push(value);
});