mirror of
https://github.com/cpvalente/ontime.git
synced 2026-08-06 16:03:52 +00:00
refactor: create utility for nested templates
This commit is contained in:
committed by
Carlos Valente
parent
7baa6a4ab9
commit
aa929fd0dc
@@ -63,7 +63,9 @@ export { customFieldLabelToKey } from './src/customField-utils/customFieldLabelT
|
||||
export { deepmerge } from './src/externals/deepmerge.js';
|
||||
|
||||
// array utils
|
||||
export { deleteAtIndex, insertAtIndex, reorderArray } from './src/array-utils/arrayUtils.js';
|
||||
export { deleteAtIndex, insertAtIndex, reorderArray } from './src/common/arrayUtils.js';
|
||||
// object utils
|
||||
export { getPropertyFromPath } from './src/common/objectUtils.js';
|
||||
|
||||
// generic utilities
|
||||
export { getErrorMessage } from './src/generic/generic.js';
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Extracts a value from a nested object using a dot-separated path
|
||||
*/
|
||||
export function getPropertyFromPath<T extends object>(path: string, obj: T): any | undefined {
|
||||
const keys = path.split('.');
|
||||
let result: any = obj;
|
||||
|
||||
// iterate through variable parts, and look for the property in the given object
|
||||
for (const key of keys) {
|
||||
if (result && typeof result === 'object' && key in result) {
|
||||
result = result[key];
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { getPropertyFromPath } from './objectUtils';
|
||||
|
||||
describe('getNestedFromTemplate', () => {
|
||||
it('should return the value of a nested property', () => {
|
||||
expect(getPropertyFromPath('a', { a: 1 })).toBe(1);
|
||||
expect(getPropertyFromPath('a.b', { a: { b: 1 } })).toBe(1);
|
||||
expect(getPropertyFromPath('a.b.c', { a: { b: { c: 1 } } })).toBe(1);
|
||||
});
|
||||
|
||||
it('should guard against values that do not exist', () => {
|
||||
expect(getPropertyFromPath('c', {})).toBe(undefined);
|
||||
expect(getPropertyFromPath('c', { a: 1 })).toBe(undefined);
|
||||
expect(getPropertyFromPath('a.c', { a: { b: 1 } })).toBeUndefined();
|
||||
expect(getPropertyFromPath('c.a', { a: { b: 1 } })).toBeUndefined();
|
||||
expect(getPropertyFromPath('a.b.b', { a: { b: { c: 1 } } })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user