Guest User

Untitled

a guest
Apr 26th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. const t = document.createTreeWalker(document.body);
  2. const closers = new WeakMap();
  3. const emit = (type,n) => {
  4. console.log(type,n);
  5. };
  6. const isBranch = n => n.nodeType == 1 || n.nodeType == 9 || n.nodeType == 10 || n.nodeType == 11;
  7. const close = n => {
  8. emit("close",n);
  9. if(closers.has(n)) {
  10. const parent = closers.get(n);
  11. closers.delete(n);
  12. close(parent);
  13. }
  14. };
  15. emit("node",t.currentNode);
  16. while(t.nextNode()) {
  17. const n = t.currentNode;
  18. emit("node",n);
  19. // if the node is a leaf or an empty branch, close its parent
  20. // else the node itself should close first
  21. // so don't close the parent yet, but move it to the closers map
  22. // and close it after this node closes
  23. let parent = n.parentNode;
  24. if(parent && parent.lastChild == n) {
  25. if(isBranch(n)) {
  26. if(!n.childNodes.length) {
  27. close(n);
  28. close(parent);
  29. } else {
  30. closers.set(n,parent);
  31. }
  32. } else {
  33. close(parent);
  34. }
  35. }
  36. }
Add Comment
Please, Sign In to add comment