Skip to content

Commit

Permalink
Merge 1afd7b6 into 5cb1dfc
Browse files Browse the repository at this point in the history
  • Loading branch information
fofi committed Feb 8, 2021
2 parents 5cb1dfc + 1afd7b6 commit 837f06a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 12 deletions.
19 changes: 9 additions & 10 deletions src/getTruthyKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,22 @@ export default getTruthyKeys
* @param collection Collection to iterate over.
* @param parseKeyFunction Function invoked per iteration. This
* function takes as parameter a key of a truthy value. The value it returns
* will be used in resulting list. Note that if this function returns a falsy
* value value, the key won't be present in resulting collection.
* @returns New list with just the keys of truthy entries, for which
* `parseKeyFunction` returned a truthy value.
* will be used in resulting list.
* @returns New list with just the keys of truthy entries.
*/
function getTruthyKeys<T extends object, TResult>(
collection: T | null | undefined,
parseKeyFunction?: (key: string) => TResult
): (string | TResult)[] {
const isFunction = _.isFunction(parseKeyFunction)

const mappedCollection = _.map(collection, function (value, key) {
if (!value) return false
return parseKeyFunction && isFunction ? parseKeyFunction(key) : key
})

return _.filter(mappedCollection) as (string | TResult)[] // Casting needed to remove `false`
return _.reduce(collection, function (acc: (string | TResult)[], value, key) {
if (value) {
const parsedKey = parseKeyFunction && isFunction ? parseKeyFunction(key) : key
acc.push(parsedKey)
}
return acc
}, [])
}

declare module 'lodash' {
Expand Down
6 changes: 4 additions & 2 deletions test/unit/getTruthyKeys.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ describe('getTruthyKeys', function () {
i: 1,
j: { a: null },
k: ['a'],
l: 'b'
l: 'b',
'': true,
false: true
}

const truthyKeys = getTruthyKeys(object)
const expectedTruthyKeys = ['a', 'f', 'g', 'i', 'j', 'k', 'l']
const expectedTruthyKeys = ['a', 'f', 'g', 'i', 'j', 'k', 'l', '', 'false']

expect(truthyKeys).to.include.members(expectedTruthyKeys)
expect(expectedTruthyKeys).to.include.members(truthyKeys)
Expand Down

0 comments on commit 837f06a

Please sign in to comment.