From 490532bce9dd61959363ff41b9f2d3d80c98bbb4 Mon Sep 17 00:00:00 2001 From: Juned Chhipa Date: Thu, 12 Dec 2024 19:25:07 +0530 Subject: [PATCH] improve clone function --- src/utils/Utils.js | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/utils/Utils.js b/src/utils/Utils.js index fec4cf78f..b88e0b72a 100644 --- a/src/utils/Utils.js +++ b/src/utils/Utils.js @@ -92,29 +92,35 @@ class Utils { return month % 12 } - static clone(source) { - if (Utils.is('Array', source)) { - let cloneResult = [] + static clone(source, visited = new WeakMap()) { + if (source === null || typeof source !== 'object') { + return source + } + + if (visited.has(source)) { + return visited.get(source) + } + + let cloneResult + + if (Array.isArray(source)) { + cloneResult = [] + visited.set(source, cloneResult) for (let i = 0; i < source.length; i++) { - cloneResult[i] = this.clone(source[i]) + cloneResult[i] = this.clone(source[i], visited) } - return cloneResult - } else if (Utils.is('Null', source)) { - // fixes an issue where null values were converted to {} - return null - } else if (Utils.is('Date', source)) { - return source - } else if (typeof source === 'object') { - let cloneResult = {} + } else if (source instanceof Date) { + cloneResult = new Date(source.getTime()) + } else { + cloneResult = {} + visited.set(source, cloneResult) for (let prop in source) { if (source.hasOwnProperty(prop)) { - cloneResult[prop] = this.clone(source[prop]) + cloneResult[prop] = this.clone(source[prop], visited) } } - return cloneResult - } else { - return source } + return cloneResult } static log10(x) {