Skip to content

Commit

Permalink
feat: "get" can access nested propeties in arrays and objects
Browse files Browse the repository at this point in the history
  • Loading branch information
andreidmt committed Aug 25, 2019
1 parent 246cb74 commit a8549ad
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/get/get.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
import { reduce } from "../reduce/reduce"

const isObject = source => typeof source === "object" && source !== null

const fromObject = (source, key) =>
source.hasOwnProperty(key) ? source[key] : undefined

const getFromPath = (propsPath, source) =>
reduce(
(acc, item) => (isObject(acc) ? fromObject(acc, item) : undefined),
source
)(propsPath)

/**
* Get value from obj property
*
* @param {string} key Property name
* @param {string} path Property name or dot path of props
* @param {object} source Source object
*
* @return {mixed}
Expand All @@ -12,8 +25,12 @@
* @example
* get( "lorem" )( { lorem: "ipsum" } ) // => "ipsum"
* get( "not-exist" )( { lorem: "ipsum" } ) // => undefined
* get( "a.b" )( { a: { b: "c" } } ) // => "c"
* get( "a.test" )( { a: { b: "c" } } ) // => undefined
*/
const get = key => source =>
typeof source === "object" ? source[key] : undefined
const get = (...propsPath) => source =>
typeof source === "object" && source !== null
? getFromPath(propsPath, source)
: undefined

export { get }
30 changes: 30 additions & 0 deletions src/get/get.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,41 @@ test("get", t => {
"Get prop from undefined // undefined"
)

t.equal(
get("not-exist-on-null")(null),
undefined,
"Get prop from null // undefined"
)

t.equal(
get("not-exist")(2),
undefined,
"Get prop from non object // undefined"
)

t.equal(
get("a", "b")({ a: { b: "lorem" } }),
"lorem",
"Get existing prop from nested objects"
)

t.equal(
get("a", "c")({ a: { b: "lorem" } }),
undefined,
"Get non-existing prop from nested objects"
)

t.equal(
get("0", "a")([{ a: "array element" }]),
"array element",
"Get existing prop from array"
)

t.equal(
get("a", 0, "b")({ a: [{ b: "array element" }] }),
"array element",
"Get existing prop from array"
)

t.end()
})

0 comments on commit a8549ad

Please sign in to comment.