Skip to content

Commit

Permalink
fix: check for object type when recursing into a property (#31)
Browse files Browse the repository at this point in the history
* fix: check for object type when recursing into a property

* fix: similar protection for `setValue`

* fix: additional test 🤔

* test: add test case
  • Loading branch information
danielroe authored Mar 31, 2022
1 parent 896430e commit 13bd920
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,25 @@ export function setValue (obj: Record<string, any>, path: string, val: any) {
const keys = path.split('.')
const _key = keys.pop()
for (const key of keys) {
if (!obj || typeof obj !== 'object') {
return
}
if (!(key in obj)) {
obj[key] = {}
}
obj = obj[key]
}
if (_key) {
if (!obj || typeof obj !== 'object') {
return
}
obj[_key] = val
}
}

export function getValue <V = any> (obj: Record<string, any>, path: string) {
for (const key of path.split('.')) {
if (!(key in obj)) {
if (!obj || typeof obj !== 'object' || !(key in obj)) {
return undefined
}
obj = obj[key]
Expand Down
21 changes: 21 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, it, expect } from 'vitest'
import { getValue, setValue } from '../src/utils'

describe('getValue', () => {
it('handles inaccessible properties', () => {
const fixture = { top: false, test: { other: false, thing: { value: 'foo' } } }
expect(getValue(fixture, 'test.thing.value')).toBe('foo')
expect(getValue(fixture, 'test.other.value')).toBe(undefined)
expect(getValue(fixture, 'top.other.value')).toBe(undefined)
})
})

describe('setValue', () => {
it('handles inaccessible properties', () => {
const fixture = { test: { other: false, thing: { value: 'foo' } } }
setValue(fixture, 'test.thing.value', 'bar')
expect(fixture.test.thing.value).toBe('bar')
setValue(fixture, 'test.other.value', 'ab')
expect(fixture.test.other).toBe(false)
})
})

0 comments on commit 13bd920

Please sign in to comment.