UNPKG

bds.js

Version:

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

71 lines (70 loc) 1.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Environment = void 0; class Environment { constructor(parent) { this.parent = parent; this.cache = new Map(); this.constant = new Map(); if (parent && !(parent instanceof Environment)) throw new Error("parent env must be instanceof Environment!"); } /** * Sets a key-value into cache * @param name * @param value * @returns */ set(name, value) { this.cache.set(name, value); return void 0; } ; const() { } ; /** * Returns value by key from cache * @param name * @returns */ get(name) { return this._recursiveGet(name); } ; _get(name) { return (this.cache.has(name) ? this.cache.get(name) ?? null : void 0); } /** * Remove value by key from cache * @param name * @returns */ remove(name) { return this.cache.delete(name); } ; /** * Recursively get from Environment to Environment * @param name * @returns */ _recursiveGet(name) { let env = this; while (true) { try { let res = env._get(name); if (res === void 0) throw new Error(`Identifier ${name} is not defined`); return res; } catch (err) { if (env?.parent) { env = env.parent; continue; } throw err /*undefined*/; } } } } exports.Environment = Environment;