Skip to content

Instantly share code, notes, and snippets.

@tabruhn
Last active November 19, 2015 20:35
Show Gist options
  • Select an option

  • Save tabruhn/7a266c5aa1cce5c6c5fa to your computer and use it in GitHub Desktop.

Select an option

Save tabruhn/7a266c5aa1cce5c6c5fa to your computer and use it in GitHub Desktop.
Prefix to Infix Mathematical Conversion and Execution
/**
* Author: Tyson Bruhn
*
* @func
* @param {String} prefix The initial prefix string.
* @return {[String, Float]} An array with the infix string and the mathematical solution
* @example
* preInfix("+52-3"); //=> "["(5+2)-3",4]"
**/
function preInfix(prefix){
var prefixchars = prefix.split("").reverse();
var nums = [];
var total = 0;
var infix = "";
var expressions = [];
prefixchars.map(
function(character){
if(character === '+' || character === '-' || character === '*' || character === '/'){
// if operator
if(nums.length < 1){
infix = getInfixForOperation(character, expressions.reverse(),"");
expressions = [];
} else if (nums.length === 1){// if there is only one number
expressions.push(character + nums[0]);
nums = [];
} else {
expressions.push(getInfixForOperation(character, nums.reverse(), '(' + infix ) + ')' );
nums = [];
}
} else {
// if number
nums.push(character);
}
}
);
if(expressions.length > 0) {
infix = getInfixForOperation("", expressions.reverse(),"");
}
function getInfixForOperation(character, nums, str){
for(var i = 0; i < nums.length-1; i++){
str = str + nums[i] + character;
};
return str + nums[nums.length-1];
}
return [infix, eval(infix)];
}
/** Tests **/
/* Stated Test Case */
assertEqualArrays("Infix with one layer", preInfix("+57-3"),["(5+7)-3",9]);
/* Test Remainder Case where the number of remaining space cannot be evenly distrubted between words */
assertEqualArrays("Two layer infix ", preInfix("-+57-53"),["(5+7)-(5-3)",10]);
assertEqualArrays("Two layer infix ", preInfix("-+572-532"),["(5+7+2)-(5-3-2)",14]);
/** Test helper **/
function assertEqual(z,x,y){
if(x!==y) throw(z + " expected " + x + "to equal " + y);
}
function assertEqualArrays(z,x,y){
if(x.length !== y.length) throw(z + " expected " + x + " to equal " + y);
for(var i in x) {
if(x[i] !== y[i]) {
throw(z + " expected " + x +" to equal " + y);
}
}
}
console.log("All test cases ran successfully");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment