diff --git a/.changeset/get-exact-key.md b/.changeset/get-exact-key.md new file mode 100644 index 0000000..2461a38 --- /dev/null +++ b/.changeset/get-exact-key.md @@ -0,0 +1,5 @@ +--- +'@layerstack/utils': patch +--- + +fix(get): Read a key spelled exactly as the path (e.g. `{ "a.b": 1 }`) before following it as a nested path diff --git a/packages/utils/src/lib/get.test.ts b/packages/utils/src/lib/get.test.ts index 5c5e397..495fe36 100644 --- a/packages/utils/src/lib/get.test.ts +++ b/packages/utils/src/lib/get.test.ts @@ -143,4 +143,21 @@ describe('get', () => { expect(get(obj, '["key.with.dots"]')).toBe('dots'); expect(get(obj, '["key[with]brackets"]')).toBe('brackets'); }); + + it('reads a key containing a period as that key', () => { + expect(get({ 'temp.max': 5 }, 'temp.max')).toBe(5); + expect(get({ 'a[0]': 'bracket' }, 'a[0]')).toBe('bracket'); + }); + + it('prefers a key spelled exactly as the path over the nested value', () => { + expect(get({ 'a.b': 'flat', a: { b: 'nested' } }, 'a.b')).toBe('flat'); + }); + + it('falls back to the path when no exact key exists', () => { + expect(get({ a: { b: 'nested' } }, 'a.b')).toBe('nested'); + }); + + it('returns defaultValue when the exact key holds undefined', () => { + expect(get({ 'a.b': undefined }, 'a.b', 'default')).toBe('default'); + }); }); diff --git a/packages/utils/src/lib/get.ts b/packages/utils/src/lib/get.ts index 2dc15b5..11c1b5e 100644 --- a/packages/utils/src/lib/get.ts +++ b/packages/utils/src/lib/get.ts @@ -67,6 +67,9 @@ function parsePath(path: string): (string | number)[] { } /** + * Read a value by key or path (`a.b`, `a[0].b`, `a["key"]`). A key spelled exactly as the path + * is read first, so `get({ "a.b": 1 }, "a.b")` is `1`. + * * See: https://github.com/angus-c/just/blob/d8c5dd18941062d8db7e9310ecc8f53fd607df54/packages/object-safe-get/index.mjs#L33C1-L61C2 */ export function get( @@ -78,6 +81,12 @@ export function get( return defaultValue as T; } + // A key spelled exactly as given (`{ "a.b": 1 }`) wins over reading it as a path + if (typeof propsArg === 'string' && propsArg in Object(obj)) { + const value = obj[propsArg]; + return value === undefined ? (defaultValue as T) : value; + } + let props: (string | number | symbol)[]; if (Array.isArray(propsArg)) {