conditions.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.takeWithoutBreak = exports.collectSwitchBranches = exports.collectIfBranches = void 0;
  4. const nodes_1 = require("./nodes");
  5. /** Returns a list of statements corresponding to a `if - else if - else` chain */
  6. function collectIfBranches(node) {
  7. const branches = [node.consequent];
  8. let endsWithElse = false;
  9. let statement = node.alternate;
  10. while (statement) {
  11. if ((0, nodes_1.isIfStatement)(statement)) {
  12. branches.push(statement.consequent);
  13. statement = statement.alternate;
  14. }
  15. else {
  16. branches.push(statement);
  17. endsWithElse = true;
  18. break;
  19. }
  20. }
  21. return { branches, endsWithElse };
  22. }
  23. exports.collectIfBranches = collectIfBranches;
  24. /** Returns a list of `switch` clauses (both `case` and `default`) */
  25. function collectSwitchBranches(node) {
  26. let endsWithDefault = false;
  27. const branches = node.cases
  28. .filter((clause, index) => {
  29. if (!clause.test) {
  30. endsWithDefault = true;
  31. }
  32. // if a branch has no implementation, it's fall-through and it should not be considered
  33. // the only exception is the last case
  34. const isLast = index === node.cases.length - 1;
  35. return isLast || clause.consequent.length > 0;
  36. })
  37. .map(clause => takeWithoutBreak(clause.consequent));
  38. return { branches, endsWithDefault };
  39. }
  40. exports.collectSwitchBranches = collectSwitchBranches;
  41. /** Excludes the break statement from the list */
  42. function takeWithoutBreak(nodes) {
  43. return nodes.length > 0 && nodes[nodes.length - 1].type === 'BreakStatement'
  44. ? nodes.slice(0, -1)
  45. : nodes;
  46. }
  47. exports.takeWithoutBreak = takeWithoutBreak;
  48. //# sourceMappingURL=conditions.js.map