Skip to content

Commit

Permalink
Update ObjectPathUtils.ts (#259)
Browse files Browse the repository at this point in the history
* Update ObjectPathUtils.ts

* Fix issue when obj have an existing getter that returns undefined
  • Loading branch information
sadortun authored Nov 4, 2024
1 parent f1a3f87 commit d79e720
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"dependencies": {
"async-mutex": "^0.5.0",
"axios": "^1.3.4",
"crypto-js": "^4.1.1",
"crypto-js": "^4.2.0",
"parse": "^5.3.0",
"prettier": "^3.0.0",
"ts-money": "^0.4.8",
Expand All @@ -54,7 +54,7 @@
"eslint": "9.13.0",
"eslint-plugin-varspacing": "1.2.2",
"eslint-plugin-vue": "9.29.1",
"jest": "^29.5.0",
"jest": "^29.7.0",
"pre-commit": "1.2.2",
"ts-jest": "^29.0.5"
},
Expand Down
24 changes: 24 additions & 0 deletions spec/ObjectPathUtils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,5 +139,29 @@ describe('ObjectPathUtils', () => {
expect(val).toStrictEqual(true);
});
});

describe('object getters', () => {
it('should return defaultVal when getter return undefined', function () {
const data = {
get a(): undefined {
return undefined;
},
};

const val = ObjectPathUtils.getPathValue(data, ['a', 'b', 'c'], 'defaultValue');
expect(val).toStrictEqual('defaultValue');
});

it('should return defaultVal when getter return not an object', function () {
const data = {
get a(): boolean {
return false;
},
};

const val = ObjectPathUtils.getPathValue(data, ['a', 'b', 'c'], 'defaultValue');
expect(val).toStrictEqual('defaultValue');
});
});
});
});
7 changes: 7 additions & 0 deletions src/ObjectPathUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,14 @@ export class ObjectPathUtils {
let o: unknown = obj;
while (a.length) {
const n = a.shift();
// o[n] can exist as a getter, but be undefined

if (typeof o !== 'object') {
return defaultVal;
}

if (n && !(n in (o as object))) {
// if (n && !(o || o.hasOwnProperty && o.hasOwnProperty(n) && n in (o as object) )) {
return defaultVal;
}
// @ts-expect-error implicit any
Expand Down

0 comments on commit d79e720

Please sign in to comment.