walker.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // @ts-check
  2. /** @typedef { import('estree').BaseNode} BaseNode */
  3. /** @typedef {{
  4. skip: () => void;
  5. remove: () => void;
  6. replace: (node: BaseNode) => void;
  7. }} WalkerContext */
  8. export class WalkerBase {
  9. constructor() {
  10. /** @type {boolean} */
  11. this.should_skip = false;
  12. /** @type {boolean} */
  13. this.should_remove = false;
  14. /** @type {BaseNode | null} */
  15. this.replacement = null;
  16. /** @type {WalkerContext} */
  17. this.context = {
  18. skip: () => (this.should_skip = true),
  19. remove: () => (this.should_remove = true),
  20. replace: (node) => (this.replacement = node)
  21. };
  22. }
  23. /**
  24. *
  25. * @param {any} parent
  26. * @param {string} prop
  27. * @param {number} index
  28. * @param {BaseNode} node
  29. */
  30. replace(parent, prop, index, node) {
  31. if (parent) {
  32. if (index !== null) {
  33. parent[prop][index] = node;
  34. } else {
  35. parent[prop] = node;
  36. }
  37. }
  38. }
  39. /**
  40. *
  41. * @param {any} parent
  42. * @param {string} prop
  43. * @param {number} index
  44. */
  45. remove(parent, prop, index) {
  46. if (parent) {
  47. if (index !== null) {
  48. parent[prop].splice(index, 1);
  49. } else {
  50. delete parent[prop];
  51. }
  52. }
  53. }
  54. }