UNPKG

bds.js

Version:

A simple interpreter written to simulate and run BDScript Language in JavaScript

49 lines (48 loc) 1.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Evaluator = void 0; class Evaluator { constructor() { } async evaluate(ast, ctx) { const res = await this.visitArgument(ast, ctx); if (ctx.options.trimOutput && typeof res === "string") return res.trim(); return res; } visit(node, ctx) { if (node.type === "string") return node.value; if (node.type === "number") return node.value; if (node.type === "operator") return node.value; if (node.type === "call") return this.visitCall(node, ctx); if (node.type === "argument") return this.visitArgument(node, ctx); throw new Error("Unknown type of " + node.type + "!"); } ; visitCall(node, ctx) { return ctx.callIdentifier(node); } ; async visitArgument(arg, ctx, map = true) { let arr = arg.child.copyWithin(-1, -1); let v = []; while (arr.length > 0) { let node = arr.shift(); let res = await this.visit(node, ctx); v.push(res); } return map ? this.mapValues(v) : v; } ; async mapValues(values) { if (values.length <= 1) return values[0]; return (await Promise.all(values.map(async (v) => String(await v)))).join(''); } } exports.Evaluator = Evaluator; Evaluator.singleton = new Evaluator();