tree.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var stdStructure = require('../structure').scopes;
  2. // depth first
  3. function mkDFSearch(treeStructure) {
  4. function depthFirst(node, fn, acc) {
  5. if(!node) return acc;
  6. //console.log(node);
  7. if(node instanceof Array) {
  8. return node.reduce(function(acc, node) {
  9. return depthFirst(node, fn, acc);
  10. }, acc);
  11. }
  12. var edges = treeStructure[node.type];
  13. edges.map(function(e) {
  14. if(!node[e]) return;
  15. acc = depthFirst(node[e], fn, acc);
  16. });
  17. return fn(node, acc);
  18. };
  19. return depthFirst;
  20. }
  21. function nextLayer(ast, struct) {
  22. if(!ast) return [];
  23. struct = struct || stdStructure;
  24. if(ast instanceof Array) {
  25. return ast.reduce(function(acc, node) {
  26. return acc.concat(nextLayer(node, struct));
  27. }, []);
  28. }
  29. var edges = struct[ast.type];
  30. var acc = [];
  31. edges.map(function(e) {
  32. if(!ast[e]) return;
  33. acc.push(ast[e]);
  34. });
  35. return acc;
  36. }
  37. module.exports = {
  38. dfSearch: mkDFSearch,
  39. nextLayer: nextLayer,
  40. };
  41. // a return value that is a choice as to whether to decend or not..., and maybe whether to add to the accumulator