infix-to-postfix-notation
Version:
A wonderful tool which converts expressions in infix notation to postfix notation using recursion.
91 lines (67 loc) • 3.52 kB
JavaScript
module.exports = (function () {
"use strict";
function PostfixNotationConverter() {}
PostfixNotationConverter.prototype = {
constructor: PostfixNotationConverter,
convertToPostfixNotation: function (infixNotation) {
if (infixNotation && infixNotation.length === 1) {
if (+infixNotation) {
return infixNotation;
} else {
return "";
}
} else {
var postfixNotation = "",
crtChar = infixNotation.charAt(0),
indexOfCrtChar = infixNotation.indexOf(crtChar);
if (+crtChar) {
postfixNotation = crtChar + this.convertToPostfixNotation(infixNotation.substring(indexOfCrtChar + 1,
infixNotation.length));
} else if (/(\+|-|\*|\/|<|>|<\=|>\=|\=\=|\=\=\=|\!\=|\!\=\=|&&|\|\|)/.test(crtChar)) {
var nextChar = infixNotation.charAt(indexOfCrtChar + 1),
indexOfNextChar = infixNotation.indexOf(nextChar);
if (nextChar === "(") {
var indexOfClosingParenthesis = getIndexOfClosingParenthesis(indexOfNextChar, infixNotation);
postfixNotation = this.convertToPostfixNotation(
infixNotation.substring(indexOfNextChar, indexOfClosingParenthesis + 1)) + crtChar + this.convertToPostfixNotation(
infixNotation.substring(indexOfClosingParenthesis + 1, infixNotation.length));
} else {
var indexOfLastDigit = getIndexOfLastDigit(indexOfNextChar, infixNotation);
postfixNotation = this.convertToPostfixNotation(
infixNotation.substring(indexOfNextChar, indexOfLastDigit + 1)) + crtChar +
this.convertToPostfixNotation(
infixNotation.substring(indexOfLastDigit + 1, infixNotation.length));
}
} else if (crtChar === "(" || crtChar === ")") {
postfixNotation = this.convertToPostfixNotation(infixNotation.substring(indexOfCrtChar + 1, infixNotation.length));
}
return postfixNotation;
}
}
};
// TODO: Improve?
function getIndexOfLastDigit(indexOfFirstDigit, infixNotation) {
var indexOfLastDigit = -1,
index = indexOfFirstDigit,
crtDigit = infixNotation.charAt(index);
while (+crtDigit && index < infixNotation.length) {
indexOfLastDigit = index;
crtDigit = infixNotation.charAt(++index);
}
return indexOfLastDigit;
}
function getIndexOfClosingParenthesis(indexOfOpenParenthesis, infixNotation) {
var indexOfClosingParenthesis = -1,
numberOfOpenParentheses = 1; // The current open parenthesis.
for (var i = indexOfOpenParenthesis + 1, j = infixNotation.length; i < j; i++) {
var crtChar = infixNotation.charAt(i);
numberOfOpenParentheses += (crtChar === "(") ? 1 : (crtChar === ")") ? -1 : 0;
if (numberOfOpenParentheses === 0) {
indexOfClosingParenthesis = i;
break;
}
}
return indexOfClosingParenthesis;
}
return new PostfixNotationConverter(); // To mimic an utility class.
})();