JSFiddle - React, Tailwind, and code Playground

by Graham Fairweather

HTML

<div>isCircularObject</div>
<div id='result1'></div>
<br />
<div>isCircular</div>
<div id='result2'></div>
<br />
<div>isCircularES5</div>
<div id='result3'></div>
<br />
<div>isCircularES5Hybrid1</div>
<div id='result4'></div>

JavaScript

function isCircular(obj, arr) {
    "use strict";

    var type = typeof obj,
        propName,
        thisVal,
        iterArr,
        lastArr;

    if (type !== "object" && type !== "function") {
        return false;
    }

    if (Object.prototype.toString.call(arr) !== '[object Array]') {
        type = typeof arr; // jslint sake
        if (!(type === "undefined" || type === null)) {
            throw new TypeError("Expected attribute to be an array");
        }

        arr = [];
    }

    arr.push(obj);
    lastArr = arr.length - 1;

    for (propName in obj) {
        thisVal = obj[propName];
        type = typeof thisVal;

        if (type === "object" || type === "function") {
            for (iterArr = lastArr; iterArr >= 0; iterArr -= 1) {
                if (thisVal === arr[iterArr]) {
                    return true;
                }
            }

            if (isCircular(thisVal, arr)) {
                return true;
            }

        }
    }

    arr.pop(obj);
    return false;
}

function isCircularES5Hybrid1(obj, arr) {
    "use strict";

    var type = typeof obj,
        propName,
        keys,
        thisVal,
        iterKeys;


    if (type !== "object" && type !== "function") {
        return false;
    }

    if (!Array.isArray(arr)) {
        type = typeof arr; // jslint sake
        if (!(type === "undefined" || type === null)) {
            throw new TypeError("Expected attribute to be an array");
        }

        arr = [];
    }

    arr.push(obj);

    for (propName in obj) {
        thisVal = obj[propName];
        type = typeof thisVal;

        if (type === "object" || type === "function") {
            if (arr.indexOf(obj[propName]) >= 0) {
                return true;
            }

            if (isCircular(thisVal, arr)) {
                return true;
            }

        }
    }

    arr.pop(obj);
    return false;
}

function isCircularES5(obj, arr) {
    "use strict";

    var type = typeof obj,
       ...