Skip to content

Commit

Permalink
refactor: create utility for nested templates
Browse files Browse the repository at this point in the history
  • Loading branch information
cpvalente committed Jan 12, 2025
1 parent 7baa6a4 commit aa929fd
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 1 deletion.
4 changes: 3 additions & 1 deletion packages/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
File renamed without changes.
18 changes: 18 additions & 0 deletions packages/utils/src/common/objectUtils.ts
Original file line number Diff line number Diff line change
@@ -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;
}
17 changes: 17 additions & 0 deletions packages/utils/src/common/objectUtilts.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});

0 comments on commit aa929fd

Please sign in to comment.