Skip to content

Commit

Permalink
support array lookup syntax, better test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
eisenivan committed Mar 10, 2020
1 parent ccbb0fc commit 0201dc7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/private/get.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
const get = (object, keys = '') => {
const get = (object, keys) => {
if (!object) { object = {} }
keys = Array.isArray(keys) ? keys : keys.replace(/\[(['"]?)([\w\d-]+)(['"]?)\]/g, '.$2').split('.')

keys = Array.isArray(keys) ? keys : `${keys}`
.replace(/\[['"]?([\w\d-]+)['"]?\]/g, '.$1')
.split('.')
.filter(x => x)

object = object[keys[0]]

if (object && keys.length > 1) {
return get(object, keys.slice(1))
}

return object
}

Expand Down
26 changes: 26 additions & 0 deletions src/private/get.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,32 @@ describe('get', () => {
expect(actual).toEqual(expected)
})

it('should return undefined if not provided a selector', () => {
const data = {
foo: { 'ba-ar': 'bars' }
}
const actual = get(data)
const expected = undefined

expect(actual).toEqual(expected)
})

it('should allow lookups in arrays', () => {
const greenArr = [
'[1]',
'1',
1
]

const data = ['foo', 'bar']
const expected = 'bar'

greenArr.forEach((x) => {
const actual = get(data, x)
expect(actual).toEqual(expected)
})
})

it('should return undefined when called with bad data', () => {
const redArr = [
undefined,
Expand Down

0 comments on commit 0201dc7

Please sign in to comment.