Browse Source

fix query

Kyle 1 month ago
parent
commit
1bb390b1c3
1 changed files with 16 additions and 5 deletions
  1. 16 5
      main.js

+ 16 - 5
main.js

@@ -38,6 +38,16 @@ function doesSolve(variable, state) {
38 38
   return expression;
39 39
 }
40 40
 
41
+function query(pieces, state) {
42
+  var depends = pieces.filter(p => !ops.includes(p) && isNaN(parseFloat(p)));
43
+  var expression = lex(pieces);
44
+  if (!validateTree(expression)) return null
45
+  return depends.reduce(
46
+    (r, d) => substituteVariable(r, d, expressionFor(d, state)),
47
+    expression
48
+  );
49
+}
50
+
41 51
 function expressionFor(variable, state) {
42 52
   var varState = state.find(x => x.name === variable);
43 53
   var notVarState = state.filter(x => x.name !== variable);
@@ -176,11 +186,12 @@ window.onload = function () {
176 186
       x => x[1] ? `${x[0]} = ${calcExpression(x[1])} = ${render(x[1])}` : ''
177 187
     )
178 188
     var result = lines.map(
179
-      l => l[0] === '?'
180
-        ? l.slice(1).map(
181
-          x => [x, expressionFor(x, state)]
182
-        ).map(x => [x[0], doesSolve(x[0], state) ? calcExpression(x[1]) : render(x[1])].join(' = ')).join('; ')
183
-        : ' '
189
+      l => {
190
+        if (l[0] !== '?') return '';
191
+        var depends = l.slice(1).filter(p => !ops.includes(p) && isNaN(parseFloat(p)));
192
+        var expression = query(l.slice(1), state)
193
+        return depends.every(x => doesSolve(x, state)) ? calcExpression(expression, state) : render(expression);
194
+      }
184 195
     )
185 196
     results.textContent = result.join('\n');
186 197
   }