Last active
April 5, 2021 13:51
-
-
Save HichamBenjelloun/94a2211bc20a1209d542273da631d576 to your computer and use it in GitHub Desktop.
Rearrange object structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
const isPlainObject = value => | |
value === Object(value) && | |
!Array.isArray(value); | |
function* leaves(node, path = []) { | |
if (!isPlainObject(node)) { | |
return yield {value: node, path}; | |
} | |
for (const [key, childNode] of Object.entries(node)) { | |
yield* leaves(childNode, [...path, key]); | |
} | |
} | |
const applyPermutation = (arr, perm) => arr.map((_, idx) => arr[perm[idx]]); | |
function rearrange(node, permutation) { | |
const output = {}; | |
for (const {path, value} of leaves(node)) { | |
_.set(output, applyPermutation(path, permutation), value); | |
} | |
return output; | |
} | |
export {rearrange}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: