feature: strict_variables, working on #9

This commit is contained in:
harttle
2016-09-26 22:49:09 +08:00
parent 38916ae864
commit be6c67a1ba
7 changed files with 110 additions and 41 deletions
+27 -12
View File
@@ -1,20 +1,30 @@
const _ = require('lodash');
const lexical = require('./lexical.js');
var scope = {
get: function(str) {
var ctx = {};
for (var i = this.scopes.length - 1; i >= 0; i--) {
if(str === undefined){
var Scope = {
safeGet: function(str) {
var i;
// get all
if (str === undefined) {
var ctx = {};
for (i = this.scopes.length - 1; i >= 0; i--) {
_.merge(ctx, this.scopes[i]);
}
return ctx;
}
// get one path
for (i = this.scopes.length - 1; i >= 0; i--) {
var v = _.get(this.scopes[i], str);
if (v !== undefined) return v;
if(str === undefined){
return ctx;
}
}
},
get: function(str){
var val = this.safeGet(str);
if (val === undefined && this.opts.strict) {
throw new Error(`[strict_variables] undefined variable: ${str}`);
}
return val;
},
set: function(k, v) {
_.set(this.scopes[this.scopes.length - 1], k, v);
return this;
@@ -28,8 +38,13 @@ var scope = {
}
};
exports.factory = function(_ctx) {
var ctx = Object.create(scope);
ctx.scopes = [_ctx || {}];
return ctx;
exports.factory = function(_ctx, opts) {
opts = _.defaults(opts, {
strict: false
});
var scope = Object.create(Scope);
scope.opts = opts;
scope.scopes = [_ctx || {}];
return scope;
};