Add objectClear & objectSpread (#1157)
* Add objectClear & objectSpread * Allow null/undefined as a source
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2021 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { objectClear } from '.';
|
||||
|
||||
describe('objectClear', (): void => {
|
||||
it('clears an object', (): void => {
|
||||
expect(
|
||||
objectClear({ a: 1, b: 2, c: { d: 3, e: 4 } })
|
||||
).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2021 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export function objectClear <T> (value: Record<string, T>): Record<string, T> {
|
||||
const keys = Object.keys(value);
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
delete value[keys[i]];
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Copyright 2017-2021 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export { objectClear } from './clear';
|
||||
export { objectSpread } from './spread';
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright 2017-2021 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { objectSpread } from '.';
|
||||
|
||||
describe('objectSpread', (): void => {
|
||||
it('spreads an object from multiple sources', (): void => {
|
||||
expect(
|
||||
objectSpread({ a: 1 }, { b: 2 }, { a: 2, c: { d: 3, e: 4 } })
|
||||
).toEqual({ a: 2, b: 2, c: { d: 3, e: 4 } });
|
||||
});
|
||||
|
||||
it('spreads an object from multiple sources (with null & undefined)', (): void => {
|
||||
expect(
|
||||
objectSpread({ a: 1 }, null, { b: 2 }, undefined, { a: 2, c: { d: 3, e: 4 } })
|
||||
).toEqual({ a: 2, b: 2, c: { d: 3, e: 4 } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017-2021 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export function objectSpread <T extends object> (dest: object, ...sources: (object | undefined | null)[]): T {
|
||||
for (let i = 0; i < sources.length; i++) {
|
||||
const src = sources[i];
|
||||
|
||||
if (src) {
|
||||
const keys = Object.keys(src);
|
||||
|
||||
for (let j = 0; j < keys.length; j++) {
|
||||
const key = keys[j];
|
||||
|
||||
(dest as Record<string, unknown>)[key] = (src as Record<string, unknown>)[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dest as T;
|
||||
}
|
||||
Reference in New Issue
Block a user