JSFiddle - React, Tailwind, and code Playground

by Graham Fairweather

JavaScript

function forEach(object, callBack) {
        var tObject = Object.prototype.toString.call(object),
            i,
            l;
    
    if (tObject !== "[object Array]" && tObject !== "[object Object]") {
        throw new TypeError("'object' must be an array or object");
    }

    if (Object.prototype.toString.call(callBack) !== "[object Function]") {
        throw new TypeError("'callBack' must be a function");
    }

    if (tObject === "[object Array]") {
        i = 0;
        l = object.length;
        
        while (i < l) {
            callBack(object[i], i);

            i += 1;
        }

        return;
    }

    for (i in object) {
        if (object.hasOwnProperty(i)) {
            callBack(object[i], i);
        }
    }
    
    return;
}

var test1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
var test2 = {
    "a": 10,
    "b": 11,
    "c": 12,
    "d": 13,
    "e": 14,
    "f": 15,
    "g": 16,
    "h": 17,
    "i": 18
};

forEach(test1, function (element, index) {
    console.log(index, element);
});

forEach(test2, function (element, index) {
    console.log(index, element);
});