JS web: use/import to Himera style web REPL.
[jackhill/mal.git] / js / env.js
1 // Node vs browser behavior
2 var env = {};
3 if (typeof module === 'undefined') {
4 var exports = env;
5 }
6
7 // Env implementation
8 function Env(outer, binds, exprs) {
9 this.data = {};
10 this.outer = outer || null;
11
12 if (binds && exprs) {
13 // Returns a new Env with symbols in binds bound to
14 // corresponding values in exprs
15 // TODO: check types of binds and exprs and compare lengths
16 for (var i=0; i<binds.length;i++) {
17 if (binds[i].value === "&") {
18 // variable length arguments
19 this.data[binds[i+1].value] = Array.prototype.slice.call(exprs, i);
20 break;
21 } else {
22 this.data[binds[i].value] = exprs[i];
23 }
24 }
25 }
26 return this;
27 }
28 Env.prototype.find = function (key) {
29 if (key in this.data) { return this; }
30 else if (this.outer) { return this.outer.find(key); }
31 else { return null; }
32 };
33 Env.prototype.set = function(key, value) { this.data[key] = value; return value; },
34 Env.prototype.get = function(key) {
35 var env = this.find(key);
36 if (!env) { throw new Error("'" + key + "' not found"); }
37 return env.data[key];
38 };
39
40 exports.Env = env.Env = Env;