Skip to content

Commit

Permalink
✨ feat(deepClone): added hasFunctionOrUndefinedValue to prevent remove
Browse files Browse the repository at this point in the history
  • Loading branch information
OysterD3 committed Apr 3, 2022
1 parent 3e751a3 commit 4f121d7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/collection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { NestedObject, NonNullish, Nullable } from "../types";
* Deep clone object or array
* @method
* @param value {T}
* @param hasFunctionOrUndefinedValue {boolean?}
* @returns {T}
* @example
* const obj = { foo: { bar: 1 } }
Expand All @@ -13,14 +14,19 @@ import type { NestedObject, NonNullish, Nullable } from "../types";
* @category Collection
* @version v0.1.0
*/
export const deepClone = <T>(value: T): T => {
export const deepClone = <T>(
value: T,
hasFunctionOrUndefinedValue = false,
): T => {
if (Array.isArray(value)) return [...value] as unknown as T;
if (typeof value === "object")
if (typeof value === "object" && hasFunctionOrUndefinedValue)
return Object.keys(value).reduce((acc, key) => {
const temp = (value as never)[key];
(acc as never)[key] = deepClone(temp);
return acc;
}, {} as T);
if (typeof value === "object" && !hasFunctionOrUndefinedValue)
return JSON.parse(JSON.stringify(value));
return value;
};

Expand Down
23 changes: 23 additions & 0 deletions src/collection/test/collection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,29 @@ describe("test deepClone", () => {
expect(obj.bar.baz).toBe(2);
expect(clone.bar.baz).toBe(4);
});

it("should erase function", () => {
const clone = deepClone<{ foo: number; bar: () => number }>({
foo: 1,
bar() {
return this.foo;
},
});
expect(clone.bar).toBe(undefined);
});

it("should not erase function", () => {
const clone = deepClone<{ foo: number; bar: () => number }>(
{
foo: 1,
bar() {
return this.foo;
},
},
true,
);
expect(clone.bar()).toBe(clone.foo);
});
});

describe("test has", () => {
Expand Down

0 comments on commit 4f121d7

Please sign in to comment.