From 9d8e71bdc762f54b12392c5abe8c49901d10f479 Mon Sep 17 00:00:00 2001 From: Andrew Courtice Date: Mon, 6 Sep 2021 09:39:51 +1000 Subject: [PATCH] feat(utilities): added top-level ignore pattern to overwrite --- packages/utilities/src/object/overwrite.ts | 6 ++++-- packages/utilities/test/overwrite.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/packages/utilities/src/object/overwrite.ts b/packages/utilities/src/object/overwrite.ts index e9a829e8..ffb1e5d1 100644 --- a/packages/utilities/src/object/overwrite.ts +++ b/packages/utilities/src/object/overwrite.ts @@ -1,10 +1,12 @@ -export default function overwrite(target: TTarget, source: TSource): TTarget | TSource { +export default function overwrite(target: TTarget, source: TSource, ignorePattern?: RegExp): TTarget | TSource { if (typeof target !== 'object' || typeof source !== 'object') { return target; } for (const prop in target) { - delete target[prop]; + if (!ignorePattern || !ignorePattern.test(prop)) { + delete target[prop]; + } } return Object.assign(target, source); diff --git a/packages/utilities/test/overwrite.test.ts b/packages/utilities/test/overwrite.test.ts index 2bc4634a..2b7406d5 100644 --- a/packages/utilities/test/overwrite.test.ts +++ b/packages/utilities/test/overwrite.test.ts @@ -28,6 +28,28 @@ describe('Utilities', () => { expect(source.e).toBeUndefined(); }); + test('Should handle a top-level ignore pattern', () => { + const source = { + a: 1, + b: null, + c: 'Hello', + d: 26, + e: [1, 2, 3], + }; + + overwrite(source, { + a: 'hello', + b: 5, + c: [1, 2], + }, /^d/); + + expect(typeof source.a).toBe('string'); + expect(typeof source.b).toBe('number'); + expect(Array.isArray(source.c)).toBe(true); + expect(source.d).toBe(26); + expect(source.e).toBeUndefined(); + }); + }); }); \ No newline at end of file