diff options
Diffstat (limited to 'graphs/js/deepCopyAndEquality/deepCopyAndEquality.js')
| -rw-r--r-- | graphs/js/deepCopyAndEquality/deepCopyAndEquality.js | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/graphs/js/deepCopyAndEquality/deepCopyAndEquality.js b/graphs/js/deepCopyAndEquality/deepCopyAndEquality.js new file mode 100644 index 0000000..4a67b6b --- /dev/null +++ b/graphs/js/deepCopyAndEquality/deepCopyAndEquality.js @@ -0,0 +1,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, +}; |
