Skip to content

Instantly share code, notes, and snippets.

@8bitDesigner
Created February 8, 2015 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 8bitDesigner/335ca2276fac4aa6cd47 to your computer and use it in GitHub Desktop.
Save 8bitDesigner/335ca2276fac4aa6cd47 to your computer and use it in GitHub Desktop.
function Expression(expr, operator) {
this.precedence = operator ? operator.precedence : 9
this.expression = (expr instanceof Array) ? expr.join(" ") : expr
}
Expression.prototype.toString = function() {
return this.expression
}
var operators = {
"^": {precedence: 4, rightAssoc: true},
"*": {precedence: 3, rightAssoc: false},
"/": {precedence: 3, rightAssoc: false},
"+": {precedence: 2, rightAssoc: false},
"-": {precedence: 2, rightAssoc: false}
}
module.exports = function(string) {
var stack = []
function parenify(expr, op, isLeft) {
return (
(expr.precedence < op.precedence) ||
(expr.precedence == op.precedence && (op.rightAssoc && isLeft))
) ? "( "+expr+" )"
: expr
}
string.split(' ').forEach(function(token) {
var op = operators[token]
, lhs, rhs
if (!op) {
stack.push(new Expression(token))
} else {
rhs = stack.pop()
lhs = stack.pop()
stack.push(new Expression([parenify(lhs, op, true), token, parenify(rhs, op)], op))
}
})
return stack.join(" ")
}
{
"name": "postfix2infix",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha test.js",
"start": "mocha test.js --watch index.js"
},
"author": "Paul Sweeney <paul@8-bitdesign.com>",
"license": "ISC",
"dependencies": {
"mocha": "^2.1.0"
}
}
var assert = require('assert')
, runner = require('./index.js')
var tests = {
"3 4 +": "3 + 4",
"3 4 + 5 *": "( 3 + 4 ) * 5",
"3 5 4 + +": "3 + 5 + 4",
"3 5 4 + *": "3 * ( 5 + 4 )",
"5 6 ^ 7 ^": "( 5 ^ 6 ) ^ 7",
"3 4 2 * 1 5 - 2 3 ^ ^ / +": "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"1 2 + 3 4 + ^ 5 6 + ^": "( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )"
}
describe('postfix2infix', function(){
Object.keys(tests).forEach(function(input) {
it ("should be able to handle: "+input, function() {
assert.equal(runner(input), tests[input])
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment