Merge pull request #663 from tcmal/master
[FIX: #658] Fixed problems with array values in deepClone snippet
This commit is contained in:
@ -7,16 +7,22 @@ Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of th
|
||||
Use `Object.keys()` and `Array.forEach()` to determine which key-value pairs need to be deep cloned.
|
||||
|
||||
```js
|
||||
|
||||
|
||||
const deepClone = obj => {
|
||||
let clone = Object.assign({}, obj);
|
||||
Object.keys(clone).forEach(
|
||||
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
|
||||
);
|
||||
return clone;
|
||||
return Array.isArray(obj) ? Array.from(clone) : clone;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
|
||||
|
||||
|
||||
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
|
||||
const b = deepClone(a); // a !== b, a.obj !== b.obj
|
||||
```
|
||||
|
||||
@ -3,6 +3,6 @@ let clone = Object.assign({}, obj);
|
||||
Object.keys(clone).forEach(
|
||||
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
|
||||
);
|
||||
return clone;
|
||||
return Array.isArray(obj) ? Array.from(clone) : clone;
|
||||
};
|
||||
module.exports = deepClone;
|
||||
module.exports = deepClone;
|
||||
|
||||
@ -7,8 +7,12 @@ test('Testing deepClone', (t) => {
|
||||
t.true(typeof deepClone === 'function', 'deepClone is a Function');
|
||||
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
|
||||
const b = deepClone(a);
|
||||
const c = [{foo: "bar"}];
|
||||
const d = deepClone(c);
|
||||
t.notEqual(a, b, 'Shallow cloning works');
|
||||
t.notEqual(a.obj, b.obj, 'Deep cloning works');
|
||||
t.notEqual(c, d, "Array shallow cloning works");
|
||||
t.notEqual(c[0], d[0], "Array deep cloning works");
|
||||
//t.deepEqual(deepClone(args..), 'Expected');
|
||||
//t.equal(deepClone(args..), 'Expected');
|
||||
//t.false(deepClone(args..), 'Expected');
|
||||
|
||||
Reference in New Issue
Block a user