-
-
Notifications
You must be signed in to change notification settings - Fork 57
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: create utility for nested templates
- Loading branch information
Showing
5 changed files
with
38 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
}); |