Skip to content

Commit

Permalink
improve clone function
Browse files Browse the repository at this point in the history
  • Loading branch information
junedchhipa committed Dec 12, 2024
1 parent 34f678c commit 490532b
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions src/utils/Utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 490532b

Please sign in to comment.