Interpreter

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests

Source Code Listing

code.ts

class Context {
  constructor(private readonly name: string) {}

  getName(): string {
    return this.name;
  }
}

type Expression = {
  interpret(context: Context): any; // Use 'any' or a more specific return type
};

class TerminalExpression implements Expression {
  interpret(context: Context): void {
    console.log(`Terminal expression for ${context.getName()}`);
  }
}

class NonterminalExpression implements Expression {
  private readonly expressions: Expression[] = [];

  addExpression(expression: Expression): void {
    this.expressions.push(expression);
  }

  interpret(context: Context): any {
    // Returns an array of results
    console.log(`Nonterminal expression for ${context.getName()}`);
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return this.expressions.map((expression) => expression.interpret(context));
  }
}

const client = {
  run(): void {
    const context = new Context("*le context");
    const root = new NonterminalExpression();
    root.addExpression(new TerminalExpression());
    root.addExpression(new TerminalExpression());
    root.interpret(context); // Call interpret and potentially use the return value
  },
};

client.run();