Created
July 27, 2017 21:45
-
-
Save dluciano/14fe65d9773fccca1e5d73456adeb7ff to your computer and use it in GitHub Desktop.
Reverse polish notation algo
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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>RPN</title> | |
<meta name="description" content="The HTML5 Herald"> | |
<meta name="author" content="SitePoint"> | |
<!--[if lt IE 9]> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script> | |
<![endif]--> | |
</head> | |
<body> | |
<script src="rpn.js"></script> | |
</body> | |
</html> |
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 node(value){ | |
var self = this; | |
self.value = value; | |
self.right = null; | |
self.left = null; | |
self.hasRight = false; | |
self.hasLeft = false; | |
self.setLeft = function(n){ | |
self.hasLeft = true; | |
self.left = n; | |
}; | |
self.setRight = function(n){ | |
self.hasRight = true; | |
self.right = n; | |
} | |
} | |
function main(){ | |
var n1 = new node("/"); | |
var n2 = new node("-"); | |
var n3 = new node("+"); | |
var n4 = new node("*"); | |
var n5= new node(25); | |
var n6 = new node(6); | |
var n7 = new node("+"); | |
var n8 = new node(4); | |
var n9 = new node(5); | |
var n10 = new node(2); | |
var n11 = new node(3); | |
n1.setLeft(n2); | |
n1.setRight(n3); | |
n2.setLeft(n4); | |
n2.setRight(n5); | |
n4.setLeft(n6); | |
n4.setRight(n7); | |
n7.setLeft(n8); | |
n7.setRight(n9); | |
n3.setLeft(n10); | |
n3.setRight(n11); | |
var result = rpn(n1); | |
console.log(result); | |
} | |
function oper(a, b, operation){ | |
switch(operation){ | |
case '+': | |
return a + b; | |
break; | |
case '-': | |
return a - b; | |
break; | |
case '*': | |
return a * b; | |
break; | |
case '/': | |
return a / b; | |
break; | |
} | |
throw "Fatal error: unknown operation"; | |
} | |
function rpn(node){ | |
var a, b; | |
if(node.hasLeft) | |
a = rpn(node.left) | |
else | |
return node.value; | |
if(node.hasRight) | |
b = rpn(node.right) | |
else | |
return node.value; | |
return oper(a, b, node.value); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment