Skip to content

Commit

Permalink
feat: Add "keys" for getting an Object's property names
Browse files Browse the repository at this point in the history
  • Loading branch information
andreidmt committed May 18, 2020
1 parent bb85fbe commit c56178e
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export { is, isNothing, not, isTrue, isFalse, isObject } from "./is/is"
export { isEmpty, isNotEmpty } from "./is-empty/is-empty"
export { isMatch } from "./is-match/is-match"
export { join } from "./join/join"
export { keys } from "./keys/keys"
export { last } from "./last/last"
export { lt } from "./lt/lt"
export { map } from "./map/map"
Expand Down
45 changes: 45 additions & 0 deletions src/keys/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Get list with names of all own properties
*
* @tag Array,Object
* @signature (source: Array|Object): string[]
*
* @param {Array|Object} source Array or Object to extract keys from
*
* @return {string[]} List of property names
*
* @example
* keys(["lorem", "ipsum"])
* // => ["0", "1"]
*
* keys({ foo: "bar", lorem: "ipsum"})
* // => ["foo", "lorem"]
*
* keys("foo"), keys(12), keys(null), etc
* // => []
*/
const keys = source => {
const type = Array.isArray(source)
? "array"
: source !== null && typeof source === "object"
? "object"
: "other"

switch (type) {
case "object":
case "array": {
const entries = Object.entries(source)
const result = []

for (let i = 0; i < entries.length; ++i) {
result.push(entries[i][0])
}

return result
}
default:
return []
}
}

export { keys }
30 changes: 30 additions & 0 deletions src/keys/keys.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import test from "tape"
import { keys } from ".."

test("keys", t => {
t.deepEquals(
keys(["test", 1, 2]),
["0", "1", "2"],
"When passing an array, should return an array of string with the index of each element"
)

t.deepEquals(
keys({ foo: "bar", lorem: "ipsum" }),
["foo", "lorem"],
"When passing an object, should return an array of strings with the key values"
)

t.deepEquals(
keys("lorem"),
[],
"When passing a string, should return an empty array"
)

t.deepEquals(
keys(12),
[],
"when passing a number, should return an empty array"
)

t.end()
})

0 comments on commit c56178e

Please sign in to comment.