summaryrefslogtreecommitdiff
path: root/graphs/js/deepCopyAndEquality/deepCopyAndEquality.js
blob: 4a67b6b2c714e3e4099893469a2bc7276ce13065 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function deepCopy(x) {
    if (x == null || x == undefined) {
        return x;
    } else if (x instanceof Date) {
        return new Date(x.valueOf());
    } else if (x instanceof Array) {
        const res = new Array();

        x.forEach((element) => res.push(deepCopy(element)));
        return res;
    } else if (typeof x === "object") {
        const res = {};

        for (const prop in x) {
            res[prop] = deepCopy(x[prop]);
        }

        const sort = (o) =>
            Object.keys(o)
                .sort()
                .reduce((final, key) => {
                    final[key] = o[key];
                    return final;
                }, {});

        return sort(res);
    } else {
        return x;
    }
}
function deepEquality(a, b) {
    if (typeof a !== typeof b) {
        return false;
    }

    return JSON.stringify(deepCopy(a)) === JSON.stringify(deepCopy(b));
}
module.exports = {
    deepCopy,
    deepEquality,
};