Skip to content

Commit

Permalink
feat(utilities): added top-level ignore pattern to overwrite
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewcourtice committed Sep 5, 2021
1 parent 40fb44a commit 9d8e71b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/utilities/src/object/overwrite.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
export default function overwrite<TTarget extends object, TSource extends object>(target: TTarget, source: TSource): TTarget | TSource {
export default function overwrite<TTarget extends object, TSource extends object>(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);
Expand Down
22 changes: 22 additions & 0 deletions packages/utilities/test/overwrite.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

});

});

0 comments on commit 9d8e71b

Please sign in to comment.