fix(deepClone): Fixed problems with array values
Would previously create an object with indices as keys. Now properly clones as array. #658
This commit is contained in:
@ -8,15 +8,25 @@ Use `Object.keys()` and `Array.forEach()` to determine which key-value pairs nee
|
||||
|
||||
```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;
|
||||
if (Array.isArray(obj)){
|
||||
let arr = [];
|
||||
obj.forEach(
|
||||
(i,v) => (arr[i] = typeof v === 'object' ? deepClone(v) : v)
|
||||
)
|
||||
return arr;
|
||||
}else {
|
||||
let clone = Object.assign({}, obj);
|
||||
Object.keys(clone).forEach(
|
||||
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
|
||||
);
|
||||
return clone;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
|
||||
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
|
||||
const b = deepClone(a); // a !== b, a.obj !== b.obj
|
||||
```
|
||||
|
||||
@ -1,8 +1,16 @@
|
||||
const deepClone = obj => {
|
||||
if (Array.isArray(obj)){
|
||||
let arr = [];
|
||||
obj.forEach(
|
||||
(i,v) => (arr[i] = typeof v === 'object' ? deepClone(v) : v)
|
||||
)
|
||||
return arr;
|
||||
}else {
|
||||
let clone = Object.assign({}, obj);
|
||||
Object.keys(clone).forEach(
|
||||
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
|
||||
);
|
||||
return clone;
|
||||
}
|
||||
};
|
||||
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