Guest User

Untitled

a guest
Mar 18th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. class Printer extends Visitor {
  2. constructor() {
  3. super()
  4. }
  5.  
  6. visitBinaryExpression(expr) {
  7. return this.prettyPrint(expr.operator, expr.left, expr.right)
  8. }
  9.  
  10. visitLiteralExpression(expr) {
  11. if (expr.value === null) return 'null'
  12.  
  13. return String(expr.value)
  14. }
  15.  
  16. visitGroupingExpression(expr) {
  17. return this.prettyPrint('group', expr.expression)
  18. }
  19.  
  20. visitUnaryExpression(expr) {
  21. return this.prettyPrint(expr.operator, expr.right)
  22. }
  23.  
  24. prettyPrint(name, ...exprs) {
  25. let arr = []
  26.  
  27. arr.push('(')
  28. arr.push(name)
  29.  
  30. for (let expr in exprs) {
  31. arr.push(' ')
  32. arr.push(exprs[expr].handle(this))
  33. }
  34.  
  35. arr.push(')')
  36. return arr.join('')
  37. }
  38.  
  39. render(expr) {
  40. return expr.handle(this)
  41. }
  42.  
  43. main() {
  44. const expr = new Binary(
  45. new Literal("12"),
  46. "*",
  47. new Binary(
  48. new Literal("10"),
  49. "-",
  50. new Literal("20")
  51. )
  52. )
  53.  
  54. return this.render(expr)
  55. }
  56. }
Add Comment
Please, Sign In to add comment