From 43332fca036dafa4664dcb71f4bd1de3d33c8d89 Mon Sep 17 00:00:00 2001 From: Alexander Rose <alexander.rose@weirdbyte.de> Date: Tue, 13 Nov 2018 23:58:49 -0800 Subject: [PATCH] added simple deepClone --- src/mol-util/object.ts | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/mol-util/object.ts b/src/mol-util/object.ts index 2ee047d59..28405be92 100644 --- a/src/mol-util/object.ts +++ b/src/mol-util/object.ts @@ -2,6 +2,7 @@ * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author David Sehnal <david.sehnal@gmail.com> + * @author Alexander Rose <alexander.rose@weirdbyte.de> */ const hasOwnProperty = Object.prototype.hasOwnProperty; @@ -54,4 +55,27 @@ export function shallowMerge<T>(source: T, ...rest: (Partial<T> | undefined)[]): } } return ret; -} \ No newline at end of file +} + +/** Simple deep clone for number, boolean, string, null, undefined, object, array */ +export function deepClone<T>(source: T): T { + if (null === source || "object" !== typeof source) return source; + + if (source instanceof Array) { + const copy: any[] = []; + for (let i = 0, len = source.length; i < len; i++) { + copy[i] = deepClone(source[i]); + } + return copy as any as T; + } + + if (source instanceof Object) { + const copy: { [k: string]: any } = {}; + for (let k in source) { + if (hasOwnProperty.call(source, k)) copy[k] = deepClone(source[k]); + } + return copy as any as T; + } + + throw new Error(`Can't clone, type "${typeof source}" unsupported`); + } \ No newline at end of file -- GitLab