Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

renameAll deleting keys #39

Merged
merged 2 commits into from Sep 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 7 additions & 13 deletions src/renameAll.js
Expand Up @@ -2,22 +2,16 @@ const curry = require('ramda/src/curry')

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

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

const to = renames[frum]

if (typeof to === 'object') {
obj[frum] = renameAll(to, obj[frum])
const newObj = {}
for (let prevKey in obj) {
const nextKey = renames[prevKey] || prevKey
if (typeof nextKey === 'object') {
newObj[prevKey] = renameAll(renames[prevKey], obj[prevKey])
} else {
obj[to] = obj[frum]
delete obj[frum]
newObj[nextKey] = obj[prevKey]
}
}

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