Skip to content

Commit

Permalink
create on internal
Browse files Browse the repository at this point in the history
  • Loading branch information
straker committed Jun 29, 2023
1 parent 827fda8 commit f4bbce4
Showing 1 changed file with 10 additions and 14 deletions.
24 changes: 10 additions & 14 deletions lib/core/utils/clone.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import cache from '../base/cache';

/**
* Deeply clones an object or array
* Deeply clones an object or array. DOM nodes or collections of DOM nodes are not deeply cloned and are instead returned as is.
* @param {Mixed} obj The object/array to clone
* @return {Mixed} A clone of the initial object or array
*/
export default function clone(obj, recursed) {
export default function clone(obj) {
return cloneRecused(obj, new Map());
}

// internal function to hide non-user facing parameters
function cloneRecused(obj, seen) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
Expand All @@ -21,22 +24,15 @@ export default function clone(obj, recursed) {
}

// handle circular references by caching the cloned object and returning it
// clear for every new call to clone so we don't return a cached value for
// a different object
const seen = cache.get('utils.clone', () => new Map());
if (!recursed) {
seen.clear();
}

if (recursed && seen.has(obj)) {
if (seen.has(obj)) {
return seen.get(obj);
}

if (Array.isArray(obj)) {
const out = [];
seen.set(obj, out);
obj.forEach(value => {
out.push(clone(value, true));
out.push(cloneRecused(value, seen));
});
return out;
}
Expand All @@ -45,7 +41,7 @@ export default function clone(obj, recursed) {
seen.set(obj, out);
// eslint-disable-next-line guard-for-in
for (const key in obj) {
out[key] = clone(obj[key], true);
out[key] = cloneRecused(obj[key], seen);
}
return out;
}

0 comments on commit f4bbce4

Please sign in to comment.