From 394ec61f5f74f0ac912f6cb11b5c5bd884e17d22 Mon Sep 17 00:00:00 2001 From: "Homa Wong (unional)" Date: Sun, 12 May 2019 17:47:06 -0700 Subject: [PATCH] fix array override and merge --- src/required.spec.ts | 22 ++++++++++++++++++---- src/required.ts | 2 +- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/required.spec.ts b/src/required.spec.ts index 6a78d22..3d0a30c 100644 --- a/src/required.spec.ts +++ b/src/required.spec.ts @@ -112,15 +112,29 @@ describe('requiredDeep()', () => { } } - const foo = new Foo() - const actual = requiredDeep({ a: {} }, undefined, { a: { b: foo } }) + class Boo extends Foo { + d() { return this.a + 1 } + } + const boo = new Boo() + const actual = requiredDeep({ a: { b: { x: 1 } } }, undefined, { a: { b: boo } }) expect(actual).toEqual({ a: { b: { - a: 1 + a: 1, + x: 1, + c: boo.c, + d: boo.d } } }) - expect(actual.a.b.c).toBe(foo.c) + }) + + test('override array', () => { + const actual = requiredDeep({ a: [1] }, { a: [2] }) + expect(actual).toEqual({ a: [2] }) + }) + + test('value add to array', () => { + expect(requiredDeep({ a: [1] }, { a: 2 })).toEqual({ a: [1, 2] }) }) }) diff --git a/src/required.ts b/src/required.ts index a55ff2d..be48c35 100644 --- a/src/required.ts +++ b/src/required.ts @@ -23,7 +23,7 @@ function merge(entries: any[], reducer: (result: any, entry: any) => any) { function deepmerge(source1: any, source2: any): any { if (typeof source1 !== 'object' || source1 === null) return source2 || source1 if (Array.isArray(source1)) { - return Array.isArray(source2) ? source1.concat(source2) : source1.push(source2) + return Array.isArray(source2) ? source2 : [...source1, source2] } return getAllKeys(source1).concat(getAllKeys(source2)).reduce((p, k) => {