Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { createSelector } = require('reselect')
- const state = {
- things: {
- byId: {
- a: { name: 'alfa', parent: null, children: ['b', 'c'] },
- b: { name: 'bravo', parent: 'a', children: [], },
- c: { name: 'charlie', parent: 'a', children: [] },
- },
- ids: ['a', 'b', 'c'],
- }
- }
- const thingSelector = createSelector([state => state.things.byId, state => state.things.ids],
- (byId, ids) => {
- byId = ids.reduce((_byId, id) => { _byId[id] = { ...byId[id] }; return _byId }, {})
- return ids.map(id => {
- const thing = byId[id]
- return Object.assign(thing, { parent: byId[thing.parent], children: thing.children.map(c => byId[c]) })
- })
- }
- )
- const things = thingSelector(state)
- function printThings(things, parent, prefix = '') {
- things.filter(t => t.parent == parent).forEach(t => {
- console.log(prefix + t.name)
- printThings(t.children, t, prefix + ' ')
- })
- }
- printThings(things)
Add Comment
Please, Sign In to add comment