refactor lookup function

This commit is contained in:
David Lechner
2020-06-08 20:56:00 -05:00
committed by David Lechner
parent e8ddf09323
commit b6be163ccb
5 changed files with 25 additions and 31 deletions
+7 -1
View File
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2020 The Pybricks Authors
import { assert, hex } from '.';
import { assert, hex, lookup } from '.';
test('assert', () => {
const assertTrue = jest.fn(() => assert(true, 'should not throw'));
@@ -16,3 +16,9 @@ test('hex', () => {
expect(hex(1, 4)).toBe('0x0001');
expect(hex(2, 8)).toBe('0x00000002');
});
test('lookup', () => {
const obj = { a: { b: { c: 'd' } } };
expect(lookup(obj, 'a.b.c')).toBe('d');
expect(lookup(obj, 'a.x.y')).toBeUndefined();
});
+15
View File
@@ -21,3 +21,18 @@ export function assert(condition: boolean, message: string): void {
export function hex(n: number, pad: number): string {
return `0x${n.toString(16).padStart(pad, '0')}`;
}
/**
* Looks up a nested property in an object.
* @param obj The object
* @param id The property path
*/
export function lookup(obj: object, id: string): string | undefined {
const value = id
.split('.')
.reduce((pv, cv) => pv && (pv as Record<string, object>)[cv], obj);
if (typeof value === 'string') {
return value;
}
return undefined;
}