Skip to content

Instantly share code, notes, and snippets.

@winstondu
Last active July 12, 2021 06:15
Show Gist options
  • Save winstondu/d917b4114e90c14715607ab00f782ea2 to your computer and use it in GitHub Desktop.
Save winstondu/d917b4114e90c14715607ab00f782ea2 to your computer and use it in GitHub Desktop.
InterpretProgram
function interpret(pgm: any): any {
let isArray = Array.isArray(pgm);
if (isArray) {
let program = pgm as any[];
switch (program[0]) {
case 'if': {
let condition: boolean = interpret(program[1]);
let trueValue = interpret(program[2]);
let falseValue = interpret(program[3]);
return condition ? trueValue : falseValue;
}
case 'gt': {
let a = interpret(program[1]) as number;
let b = interpret(program[2]) as number;
return a > b;
}
case 'lt': {
let a = interpret(program[1]) as number;
let b = interpret(program[2]) as number;
return a < b;
}
case 'eq': {
let a = interpret(program[1]) as number;
let b = interpret(program[2]) as number;
return a === b;
}
// operators
default: {
return handleOperators(program) as any;
}
}
} else {
return pgm;
}
}
let handleOperators = (program: any[]): number => {
let a = interpret(program[1]) as number;
let b = interpret(program[2]) as number;
let operator = program[0];
switch (operator) {
case 'add': {
return a + b;
}
case 'sub': {
return a - b;
}
case 'mul': {
return a * b;
}
case 'div': {
return a / b;
}
default: {
return 0;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment