Skip to content
Snippets Groups Projects
Unverified Commit 88452470 authored by Sergei Zharinov's avatar Sergei Zharinov Committed by GitHub
Browse files

feat: Add `assignKeys` utility function (#23483)

parent 3fb7cb1f
No related branches found
No related tags found
No related merge requests found
import { assignKeys } from './assign-keys';
describe('util/assign-keys', () => {
it('should assign values from right to left for specified keys', () => {
type Left = { a: number; b: number };
const left: Left = { a: 1, b: 2 };
type Right = { a?: number; b?: number; c?: number };
const right: Right = { a: 3, c: 4 };
const result = assignKeys(left, right, ['a', 'b']);
expect(result).toEqual({
a: 3,
b: 2,
});
expect(result).toBe(left);
});
});
import is from '@sindresorhus/is';
/**
* Assigns non-nullish values from `right` to `left` for the given `keys`.
*/
export function assignKeys<
Left extends { [key in K]?: Right[key] },
Right extends { [key in K]?: any },
K extends keyof Right
>(left: Left, right: Right, keys: K[]): Left {
for (const key of keys) {
const val = right[key];
if (!is.nullOrUndefined(val)) {
left[key] = val;
}
}
return left;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment