|
| 1 | +// function for object deep cloning |
| 2 | +// the main idea of deep cloning is to create a complete copy of an object whose |
| 3 | +// properties do not share the same references (point to the same underlying values) |
| 4 | +// as those of the source object from which the copy was made |
| 5 | + |
| 6 | +function deepClone(obj: any) { |
| 7 | + if (obj === null) return null; |
| 8 | + |
| 9 | + // create a shallow clone |
| 10 | + let clone = Object.assign({}, obj); |
| 11 | + |
| 12 | + // iterate though all keys and either assign a primitive if the value in the |
| 13 | + // original object is a primitive or recursively call the clone function |
| 14 | + // if the value is an object |
| 15 | + Object.keys(clone).forEach((key) => ( |
| 16 | + clone[key] = |
| 17 | + typeof obj[key] === 'object' ? |
| 18 | + deepClone(obj[key]) : |
| 19 | + obj[key] |
| 20 | + ), |
| 21 | + ); |
| 22 | + |
| 23 | + // if an object is an array set its length to that of the original and create |
| 24 | + // a copy using Array.from method, if we don't do it the arrays will be just objects |
| 25 | + if (Array.isArray(obj)) { |
| 26 | + clone.length = obj.length; |
| 27 | + return Array.from(clone); |
| 28 | + } |
| 29 | + |
| 30 | + return clone; |
| 31 | +} |
| 32 | + |
| 33 | +// ---------------------------------------------------------------------------- |
| 34 | +// Tests |
| 35 | +// ---------------------------------------------------------------------------- |
| 36 | + |
| 37 | +const originalObject = { |
| 38 | + string: 'I am a sting', |
| 39 | + array: [1, 2, 3, [4, 5, 6]], |
| 40 | + innerObject: { |
| 41 | + number: 1, |
| 42 | + innerInnerObject: { |
| 43 | + number: 2, |
| 44 | + array: [4, 5, 6], |
| 45 | + }, |
| 46 | + }, |
| 47 | +}; |
| 48 | + |
| 49 | +const deepClonedObject = deepClone(originalObject); |
| 50 | +const shallowClonedObject = Object.assign({}, originalObject); |
| 51 | + |
| 52 | +console.log('originalObject:'); |
| 53 | +console.log(originalObject); |
| 54 | +console.log('deepClonedObject:'); |
| 55 | +console.log(deepClonedObject); |
| 56 | +console.log('shallowClonedObject:'); |
| 57 | +console.log(shallowClonedObject); |
| 58 | + |
| 59 | +// should be false |
| 60 | +console.log('Should be false: '); |
| 61 | +console.log(originalObject === deepClonedObject); |
| 62 | + |
| 63 | +// should be false |
| 64 | +console.log('Should be false: '); |
| 65 | +console.log(originalObject === shallowClonedObject); |
| 66 | + |
| 67 | +// should be false because deep clone houses the entire copied inner object, not just the pointer to an address |
| 68 | +console.log('Should be false: '); |
| 69 | +console.log(originalObject.innerObject === deepClonedObject.object); |
| 70 | + |
| 71 | +// should be true because shallow copy just stores a pointer to an address |
| 72 | +console.log('Should be true: '); |
| 73 | +console.log(originalObject.innerObject === shallowClonedObject.innerObject); |
| 74 | + |
0 commit comments