Created
February 8, 2015 01:08
-
-
Save 8bitDesigner/335ca2276fac4aa6cd47 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
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(" ") | |
} |
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
{ | |
"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" | |
} | |
} |
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
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