Skip to content

Commit 5cf82b3

Browse files
committed
Internal lib - Add utility function to check existence of nested attr in obj
1 parent 006091a commit 5cf82b3

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/lib.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,16 @@ export function applyDataLabel(func, data, fallbackValue, config) {
17541754
return isValid ? value : fallbackValue;
17551755
}
17561756

1757+
export function hasDeepProperty(obj, path) {
1758+
return path.split('.').every(key => {
1759+
if (obj !== null && typeof obj === 'object' && key in obj) {
1760+
obj = obj[key];
1761+
return true;
1762+
}
1763+
return false;
1764+
});
1765+
}
1766+
17571767
const lib = {
17581768
XMLNS,
17591769
abbreviate,
@@ -1797,6 +1807,7 @@ const lib = {
17971807
getMissingDatasetAttributes,
17981808
getPalette,
17991809
giftWrap,
1810+
hasDeepProperty,
18001811
interpolateColorHex,
18011812
isFunction,
18021813
isSafeValue,

tests/lib.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
functionReturnsString,
3535
generateSpiralCoordinates,
3636
getMissingDatasetAttributes,
37+
hasDeepProperty,
3738
hslToRgb,
3839
interpolateColorHex,
3940
isFunction,
@@ -1846,3 +1847,22 @@ describe('applyDataLabel', () => {
18461847
)).toStrictEqual('p-12-s');
18471848
});
18481849
});
1850+
1851+
describe('hasDeepProperty', () => {
1852+
const obj = {
1853+
attr0: {
1854+
attr1: {
1855+
attr2: {
1856+
attr3 : 'A'
1857+
}
1858+
}
1859+
}
1860+
}
1861+
test('checks if an object as a deep property', () => {
1862+
expect(hasDeepProperty(obj, 'attr0')).toBe(true)
1863+
expect(hasDeepProperty(obj, 'attr0.attr1')).toBe(true)
1864+
expect(hasDeepProperty(obj, 'attr0.attr1.attr2')).toBe(true)
1865+
expect(hasDeepProperty(obj, 'attr0.attr1.attr2.attr3')).toBe(true)
1866+
expect(hasDeepProperty(obj, 'attr0.attr1.attr2.attr3.attr4')).toBe(false)
1867+
})
1868+
})

0 commit comments

Comments
 (0)