Skip to content

Commit

Permalink
Merge pull request #2 from hugebdu/master
Browse files Browse the repository at this point in the history
pass key/index to callback
  • Loading branch information
Kikobeats committed Jul 11, 2019
2 parents c216087 + 16067d7 commit e63e814
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
8 changes: 4 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

const { map, isArray, isObject, isPlainObject, mapValues } = require('lodash')

const mapValuesDeep = (obj, fn) =>
const mapValuesDeep = (obj, fn, key) =>
isArray(obj)
? map(obj, innerObj => mapValuesDeep(innerObj, fn))
? map(obj, (innerObj, idx) => mapValuesDeep(innerObj, fn, idx))
: isPlainObject(obj)
? mapValues(obj, val => mapValuesDeep(val, fn))
? mapValues(obj, (val, key) => mapValuesDeep(val, fn, key))
: isObject(obj)
? obj
: fn(obj)
: fn(obj, key)

module.exports = mapValuesDeep
15 changes: 15 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const test = require('ava')
const map = require('..')

const square = (value, key) => value * value
const keyPlusValue = (value, key) => key + value

test('transforms simple object', t => {
t.deepEqual(map({ two: 2, three: 3 }, square), { two: 4, three: 9 })
Expand All @@ -27,6 +28,20 @@ test('transforms array with nested objects/arrays', t => {
])
})

test('passes object key to mapper function', t => {
t.deepEqual(
map({ key1: 'foo', key2: 'bar' }, keyPlusValue),
{ key1: 'key1foo', key2: 'key2bar' }
)
})

test('passes array key (index) to mapper function', t => {
t.deepEqual(
map([0, 2, 4], keyPlusValue),
[0, 3, 6]
)
})

test('Do nothing on non plain objects', t => {
const now = new Date()
t.deepEqual(map(now, square), now)
Expand Down

0 comments on commit e63e814

Please sign in to comment.