Skip to content

Instantly share code, notes, and snippets.

@jocafi
Last active January 7, 2019 10:13
Show Gist options
  • Save jocafi/90dbaa63934d53b3b424bf9f90b4ffa0 to your computer and use it in GitHub Desktop.
Save jocafi/90dbaa63934d53b3b424bf9f90b4ffa0 to your computer and use it in GitHub Desktop.
DeepCopy in TypeScript
import { Injectable } from "@angular/core";
/**
* Created by Joao Araujo (jocafi) on November 2018
*
* UtilService implements some util methods which can be used along the App development.
*
*/
@Injectable()
export class UtilService {
/**
* Returns a deep copy of a object. It replaces the command JSON.parse(JSON.stringify(object)).
*
* <p>Best performance ran at https://jsperf.com/deep-copy-vs-json-stringify-json-parse/51
*
* @param obj Object to be copied.
* @returns {any} Copy of object.
*/
deepCopyObject(object) {
let r, i, l;
if (typeof object !== "object") {
return object;
}
if (!object) {
return object;
}
if (object.constructor === Array) {
r = [];
l = object.length;
for (i = 0; i < l; i++) {
r[i] = this.deepCopyObject(object[i]);
}
return r;
}
r = {};
for (i of object) {
r[i] = this.deepCopyObject(object[i]);
}
return r;
}
// alternative found at
// https://dev.to/ptasker/best-way-to-copy-an-object-in-javascript-827
deepCopy(obj) {
if (typeof obj === "object") {
return Object.keys(obj)
.map(k => ({ [k]: this.deepCopy(obj[k]) }))
.reduce((a, c) => Object.assign(a, c), {});
} else if (Array.isArray(obj)) {
return obj.map(this.deepCopy)
}
return obj;
}
deepCopyObjectInto(source, dest) {
const sourceCopy = this.deepCopy(source);
if (typeof sourceCopy !== "object" || sourceCopy == null) {
throw new Error("Only objects can be copied. The source object has type of '" + (typeof source) + "'.");
}
if (typeof dest !== "object" || dest == null) {
throw new Error("Only objects can be copied. The destination object has type of '" + (typeof dest) + "'.");
}
Object.keys(sourceCopy)
.map(k => {
dest[k] = this.deepCopy(sourceCopy[k]);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment