Skip to content

Commit

Permalink
fixing renameAll to allow a from and a to to have the same name
Browse files Browse the repository at this point in the history
  • Loading branch information
jesspoemape committed Sep 1, 2020
1 parent 040773c commit 0cdc978
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
23 changes: 17 additions & 6 deletions src/renameAll.js
Expand Up @@ -2,22 +2,33 @@ const curry = require('ramda/src/curry')

// renameAll :: { k: v } -> { k: v } -> { k: v }
const renameAll = (renames, obj) => {
obj = Object.assign({}, obj)
const newObj = {}
const tosMap = {}

for (let k in obj) {
newObj[k] = obj[k]
}

for (let frum in renames) {
if (!(frum in obj)) continue
if (!(frum in obj)) {
continue
}

const to = renames[frum]

if (typeof to === 'object') {
obj[frum] = renameAll(to, obj[frum])
newObj[frum] = renameAll(to, obj[frum])
} else {
obj[to] = obj[frum]
delete obj[frum]
tosMap[to] = true
newObj[to] = obj[frum]

if (!tosMap[frum]) {
delete newObj[frum]
}
}
}

return obj
return newObj
}

module.exports = curry(renameAll)
12 changes: 9 additions & 3 deletions test/renameAll.js
Expand Up @@ -8,23 +8,29 @@ describe('renameAll', () => {
name: 'bird',
sounds: {
call: 'chirp'
}
},
title: 'My title',
latestTitle: 'haha (business)',
}

const renames = {
color: 'appearance',
count: 'number',
sounds: {
call: 'say'
}
},
latestTitle: 'title',
title: 'updatedTitle',
}

const expected = {
appearance: 'red',
name: 'bird',
sounds: {
say: 'chirp'
}
},
title: 'haha (business)',
updatedTitle: 'My title',
}

it('renames multiple nested properties on an object using a name-map', () =>
Expand Down

0 comments on commit 0cdc978

Please sign in to comment.