Guest User

Untitled

a guest
Apr 26th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. const { createSelector } = require('reselect')
  2.  
  3. const state = {
  4. things: {
  5. byId: {
  6. a: { name: 'alfa', parent: null, children: ['b', 'c'] },
  7. b: { name: 'bravo', parent: 'a', children: [], },
  8. c: { name: 'charlie', parent: 'a', children: [] },
  9. },
  10. ids: ['a', 'b', 'c'],
  11. }
  12. }
  13.  
  14. const thingSelector = createSelector([state => state.things.byId, state => state.things.ids],
  15. (byId, ids) => {
  16. byId = ids.reduce((_byId, id) => { _byId[id] = { ...byId[id] }; return _byId }, {})
  17. return ids.map(id => {
  18. const thing = byId[id]
  19. return Object.assign(thing, { parent: byId[thing.parent], children: thing.children.map(c => byId[c]) })
  20. })
  21. }
  22. )
  23.  
  24. const things = thingSelector(state)
  25.  
  26. function printThings(things, parent, prefix = '') {
  27. things.filter(t => t.parent == parent).forEach(t => {
  28. console.log(prefix + t.name)
  29. printThings(t.children, t, prefix + ' ')
  30. })
  31. }
  32.  
  33. printThings(things)
Add Comment
Please, Sign In to add comment