Skip to content

Commit

Permalink
Merge 4e4aa15 into 0c5cead
Browse files Browse the repository at this point in the history
  • Loading branch information
tranhl committed Apr 25, 2024
2 parents 0c5cead + 4e4aa15 commit 5417d1b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
24 changes: 18 additions & 6 deletions packages/dynamoose/lib/utils/deep_copy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import * as objectUtils from "js-object-utilities";

export default function deep_copy<T> (obj: T): T {
export default function deep_copy<T> (obj: T, refs = new Set()): T {
let copy: any;

// Handle Date
Expand All @@ -12,7 +10,7 @@ export default function deep_copy<T> (obj: T): T {

// Handle Array
if (obj instanceof Array) {
copy = obj.map((i) => deep_copy(i));
copy = obj.map((i) => deep_copy(i, refs));
return copy;
}

Expand Down Expand Up @@ -47,14 +45,28 @@ export default function deep_copy<T> (obj: T): T {

// Handle Object
if (obj instanceof Object) {
refs.add(obj);

if (obj.constructor !== Object) {
copy = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
} else {
copy = {};
}

for (const attr in obj) {
if (Object.prototype.hasOwnProperty.call(obj, attr) && !objectUtils.isCircular(obj as any, attr)) {
copy[attr] = deep_copy(obj[attr]);
if (Object.prototype.hasOwnProperty.call(obj, attr)) {
const value = obj[attr];
const isObjValue = typeof value === "object" && !Array.isArray(value) && value !== null;

if (isObjValue) {
const isCircular = refs.has(value);
// Omit circular property from copy
if (isCircular) continue;

refs.add(value);
}

copy[attr] = deep_copy(value, refs);
}
}
return copy;
Expand Down
9 changes: 9 additions & 0 deletions packages/dynamoose/test/utils/deep_copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ describe("utils.deep_copy", () => {
expect(copy).toStrictEqual({"a": 1, "b": "test", "c": {"d": 100, "e": 200}});
});

it("Should return a deep copy of the passed object ignoring circular references", () => {
const original = {"a": 1, "b": "test", "c": {"d": 100, "e": 200, "f": {"g": 300}}};
original.self = original;
original.c.c = original.c;
original.c.f.c = original.c;
const copy = utils.deep_copy(original);
expect(copy).toStrictEqual({"a": 1, "b": "test", "c": {"d": 100, "e": 200, "f": {"g": 300}}});
});

it("Should return a deep copy of the passed class instances", () => {
class PersonWrapper {
constructor (name, age) {
Expand Down

0 comments on commit 5417d1b

Please sign in to comment.