deep-copy
This microlibrary provides a deep copy of a given object or array.
Usage
Install the library:
npm install @ardentia/deep-copy
Then, in the file where you want to use it:
import getItemCopy from '@ardentia/deep-copy';
const copy = getItemCopy(<value>);
const getItemCopy = require('@ardentia/deep-copy/node').default;
const copy = getItemCopy(<value>);
The library is built to be ES6-, TypeScript and node.js-compatible.
Examples:
The values of the given object are recursively traversed and are also deep copied in case they are not primitive types. If the value is a primitive type, a copy by value is returned.
const myCustomObject = {
numberVal: 1,
stringVal: 'string',
arrayVal: [{ foo: 'bar' }, 1, 2, 3],
objectVal: { foo: 'bar', innerArray: [1, 2, 3] }
};
const objectCopy = getItemCopy(myCustomObject);
console.log(Object.is(objectCopy, myCustomObject));
console.log(Object.is(objectCopy.numberVal, myCustomObject.numberVal));
console.log(Object.is(objectCopy.stringVal, myCustomObject.stringVal));
console.log(Object.is(objectCopy.arrayVal, myCustomObject.arrayVal));
console.log(Object.is(objectCopy.arrayVal[0], myCustomObject.arrayVal[0]));
console.log(Object.is(objectCopy.objectVal, myCustomObject.objectVal));
console.log(Object.is(objectCopy.objectVal.innerArray, myCustomObject.objectVal.innerArray));
Same deep copy logic applies to array members:
const myCustomArray = [
1,
'string',
{ foo: 'bar', innerArray: [1, 2, 3] },
[{ foo: 'bar'}, 1, 2, 3]
];
const arrayCopy = getItemCopy(myCustomArray);
console.log(Object.is(arrayCopy, myCustomArray));
console.log(Object.is(arrayCopy[0], myCustomArray[0]));
console.log(Object.is(arrayCopy[1], myCustomArray[1]));
console.log(Object.is(arrayCopy[2], myCustomArray[2]));
console.log(Object.is(arrayCopy[2].innerArray, myCustomArray[2].innerArray));
console.log(Object.is(arrayCopy[3], myCustomArray[3]));
console.log(Object.is(arrayCopy[3][0], myCustomArray[3][0]));
Note: If the object you are attempting to copy contains children that recursively reference their parent object, the call to getItemCopy(...)
will cause a range error exception: Range Error: Maximum call stack size exceeded
. If such an object structure is possible in your case, you need to place the call to getItemCopy(...)
in a try-catch construction:
import getItemCopy from '@ardentia/deep-copy';
const rootObj = {
childA: null,
childB: null
};
const childA = {
a1: 'a1',
a2: 'a2',
root: rootObj
};
rootObj.childA = childA;
const childB = {
b1: 'b1',
b2: 'b2',
root: rootObj
};
try {
const result = getItemCopy(rootObj);
} catch(ex) {
}
Local Development
- Fork the project and clone it locally
npm install
to install the library dependenciesnpm install -g typescript
to install TypeScript globallynpm test
to run testsnpm run build
to build for production