diff --git a/package.json b/package.json index a7d6a08..b538495 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@goplan-finance/utils", - "version": "1.1.1", + "version": "1.1.2", "description": "", "keywords": [ "finance", @@ -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", @@ -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" }, diff --git a/spec/ObjectPathUtils.spec.ts b/spec/ObjectPathUtils.spec.ts index f3252b0..0659d07 100644 --- a/spec/ObjectPathUtils.spec.ts +++ b/spec/ObjectPathUtils.spec.ts @@ -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'); + }); + }); }); }); diff --git a/src/ObjectPathUtils.ts b/src/ObjectPathUtils.ts index e94cd6c..c5b8cf1 100644 --- a/src/ObjectPathUtils.ts +++ b/src/ObjectPathUtils.ts @@ -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