diff options
Diffstat (limited to 'util')
| -rw-r--r-- | util/deep_assign.ts | 28 | ||||
| -rw-r--r-- | util/deep_assign_test.ts | 24 | ||||
| -rw-r--r-- | util/test.ts | 1 |
3 files changed, 53 insertions, 0 deletions
diff --git a/util/deep_assign.ts b/util/deep_assign.ts new file mode 100644 index 000000000..4857e18b5 --- /dev/null +++ b/util/deep_assign.ts @@ -0,0 +1,28 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +export function deepAssign(target: object, ...sources: object[]): object { + for (let i = 0; i < sources.length; i++) { + const source = sources[i]; + if (!source || typeof source !== `object`) { + return; + } + Object.entries(source).forEach(([key, value]) => { + if (value instanceof Date) { + target[key] = new Date(value); + return; + } + if (!value || typeof value !== `object`) { + target[key] = value; + return; + } + if (Array.isArray(value)) { + target[key] = []; + } + // value is an Object + if (typeof target[key] !== `object` || !target[key]) { + target[key] = {}; + } + deepAssign(target[key], value); + }); + } + return target; +} diff --git a/util/deep_assign_test.ts b/util/deep_assign_test.ts new file mode 100644 index 000000000..36be979d8 --- /dev/null +++ b/util/deep_assign_test.ts @@ -0,0 +1,24 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { test } from "../testing/mod.ts"; +import { assertEquals, assert } from "../testing/asserts.ts"; +import { deepAssign } from "./deep_assign.ts"; + +test(function deepAssignTest() { + const date = new Date("1979-05-27T07:32:00Z"); + const reg = RegExp(/DENOWOWO/); + const obj1 = { deno: { bar: { deno: ["is", "not", "node"] } } }; + const obj2 = { foo: { deno: date } }; + const obj3 = { foo: { bar: "deno" }, reg: reg }; + const actual = deepAssign(obj1, obj2, obj3); + const expected = { + foo: { + deno: new Date("1979-05-27T07:32:00Z"), + bar: "deno" + }, + deno: { bar: { deno: ["is", "not", "node"] } }, + reg: RegExp(/DENOWOWO/) + }; + assert(date !== expected.foo.deno); + assert(reg !== expected.reg); + assertEquals(actual, expected); +}); diff --git a/util/test.ts b/util/test.ts new file mode 100644 index 000000000..a617c10ab --- /dev/null +++ b/util/test.ts @@ -0,0 +1 @@ +import "./deep_assign_test.ts"; |
