Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict"
- function operation(letter, priority, associativity, f) {
- this.letter = letter,
- this.priority = priority,
- this.associativity = associativity
- this.f = f
- }
- function TranslateInfixToPostfix(infix, operators){
- infix = infix.replace(/\s+/g, "");
- let stack = [];
- let result = "";
- result += FillStack(infix, result, stack, operators);
- while (stack.length > 0){
- result += stack.pop() + ' ';
- }
- return result;
- }
- function EvaluatePostfix(postfix, operators){
- let stack = [];
- postfix = postfix.split(' ');
- for (let i = 0; i < postfix.length - 1; i++){
- let token = postfix[i];
- if (IsNumber(token)) {
- stack.push(parseFloat(token));
- } else {
- let y = stack.pop();
- let x = stack.pop();
- stack.push(operators[token].f(x,y));
- }
- }
- return stack.pop();
- }
- function FillStack(infix, postfix, stack, operators) {
- for (let i = 0; i < infix.length; i++) {
- let token = infix.charAt(i);
- if (IsNumber(token)) {
- while (IsNumber(infix.charAt(i + 1))) {
- postfix += token;
- token = infix.charAt(i + 1);
- i++;
- }
- postfix += token + ' ';
- }
- else if (operators[token]) {
- postfix = HandleOperations(operators[token], stack, operators, postfix);
- } else if (token == '(') {
- stack.push(token);
- } else if (token == ')') {
- postfix = HandleBrace(stack, postfix);
- }
- }
- return postfix;
- }
- function IsNumber(symbol) {
- return symbol >= "0" && symbol <= "9";
- }
- function HandleBrace(stack, postfix) {
- while(stack[stack.length - 1] != '(') {
- postfix += stack.pop() + ' ';
- }
- stack.pop();
- return postfix;
- }
- function HandleOperations(op1, stack, ops, postfix) {
- let op2 = ops[stack[stack.length - 1]];
- while (op2 &&
- ((op1.associativity == "Left" && (op1.priority <= op2.priority)) ||
- (op1.associativity == "Right" && (op1.priority < op2.priority)))) {
- postfix += op2.letter + ' ';
- stack.pop();
- op2 = ops[stack[stack.length - 1]];
- }
- stack.push(op1.letter);
- return postfix;
- }
- test();
- function test() {
- let operators = {
- "+": new operation("+", "1", "Left", (x, y) => { return x + y }),
- "-": new operation("-", "1", "Left", (x, y) => { return x - y }),
- "*": new operation("*", "2", "Left", (x, y) => { return x * y }),
- "/": new operation("/", "2", "Left", (x, y) => { return x / y }),
- "^": new operation("^", "3", "Right", (x, y) => { return Math.pow(x,y) })
- };
- let infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
- let postfix = TranslateInfixToPostfix(infix, operators);
- let value = EvaluatePostfix(postfix, operators);
- }
Advertisement
Add Comment
Please, Sign In to add comment