Created
July 6, 2022 14:47
-
-
Save theAlgorithmist/78b89be60fc51857c2891be5c9df80d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public evaluate(variables: Array<expressionOperand>): expressionValue | |
{ | |
if (this._expressionStack.length === 0) return false; | |
if (variables.length != this._variables.length) return false; | |
const len: number = variables.length; | |
let j: number; | |
for (j = 0; j < len; ++j) { | |
if (!this.__isValidOperand(variables[j])) return false; | |
} | |
let token = ""; | |
let tokenType = ""; | |
const opStack:Array<expressionOperand> = new Array<expressionOperand>(); | |
let arg1: expressionOperand; | |
let arg2: expressionOperand; | |
let i: number; | |
let f: ExpressionFcn; | |
i = 0; | |
while (i < this._expressionStack.length) | |
{ | |
// in reverse order, type is before value | |
tokenType = this._expressionStack[i]; | |
token = this._expressionStack[i+1]; | |
switch (tokenType) | |
{ | |
case this.IS_NUMBER: | |
opStack.push(+token); | |
break; | |
case this.IS_ONE_ARG_FUNCTION: | |
arg1 = opStack.pop() as expressionOperand; | |
f = (this as unknown as Record<string, ExpressionFcn>)[token] as ExpressionFcn; | |
if (f === undefined) return false; // unsupported function | |
opStack.push( f(arg1) ); | |
break; | |
case this.IS_TWO_ARG_FUNCTION: | |
arg1 = opStack.pop() as expressionOperand; | |
arg2 = opStack.pop() as expressionOperand; | |
f = (this as unknown as Record<string, ExpressionFcn>)[token] as ExpressionFcn; | |
if (f === undefined) return false; | |
opStack.push( f(arg1, arg2) ); | |
break; | |
case this.IS_VARIABLE: | |
for (j = 0; j < len; ++j) { | |
if( token === this._variables[j] ) opStack.push(variables[j]); | |
} | |
break; | |
case this.IS_STR_LITERAL: | |
opStack.push(token.toString()); | |
break; | |
case this.IS_ARRAY: | |
opStack.push(token.toString()) | |
break; | |
default: | |
return false; // invalid token | |
} | |
i += 2; | |
} | |
return opStack[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment