Skip to content

Commit

Permalink
fix(clone): correct clone reference issue
Browse files Browse the repository at this point in the history
Fixed an issue which would set a reference between
the cloned object and the orginal when an object had
a value of another object.

Example:
```
const obj1 = { a: { b: 1 } };
const obj2 = clone(a);

obj2.a.b = 2;

console.log(obj1); // => { a: { b: 2 } }
console.log(obj2); // => { a: { b: 2 } }
```

After fix:
```
console.log(obj1); // => { a: { b: 1 } }
console.log(obj2); // => { a: { b: 2 } }
```
  • Loading branch information
Sean Hamilton committed Jul 1, 2019
1 parent 618dfcb commit cc26f32
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/clone.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// o
import { valid } from './util';
import is from './is';
import empty from './empty';

/**
Expand Down Expand Up @@ -34,9 +35,19 @@ function clone(obj: OObject): OObject {

// for each key in the object
Object.keys(obj).forEach((key: string) => {
// add the value from the original object to the same
// key in the new object
result[key] = obj[key];
// get the value at the current key
const val: any = obj[key];

// if the value is an object
if (is(val)) {
// set the value on the result object as
// the cloned value object
result[key] = clone(val);
} else {
// add the value from the original object to the same
// key in the new object
result[key] = obj[key];
}
});

// return the new object
Expand Down

0 comments on commit cc26f32

Please # to comment.