programming exercise
HTML
<h1>Test results:</h1>
<ul id="results"></ul>
CSS
ul {
list-style: none;
}
li {
padding: 0.5em;
}
JavaScript
//
// This function is passed a string and should return a number.
// The input string is like these:
// "5" -> returns 5
// "+ 2 4" -> returns 6
// "* + 1 2 - 8 6" -> returns 6
// The input is a sequence of space separated tokens.
// Each token is a number or one of the operators + - * /.
// Numbers are expressions that evaluate to themselves.
// Operators are followed by two expressions and evaluate to the sum, difference
// product, or quotient of the value of the expressions.
//
function evaluate(str) {
var a = [];
var tokens = str.split(' ');
for (var i = tokens.length - 1; i >= 0; i--) {
switch(tokens[i]) {
case '*':
a.push(a.pop() * a.pop());
break;
case '+':
a.push(a.pop() + a.pop());
break;
case '-':
a.push(a.pop() - a.pop());
break;
case '/':
a.push(a.pop() / a.pop());
break;
default:
a.push(parseFloat(tokens[i]));
break;
}
}
if (a.length == 1) {
// success
return a[0];
} else {
console.log("error in parsing the string: " + str);
return false;
}
}
var tests = ["7", "* 7.7 2.1", "/ 2 4", "* + 1 2 - 8 6",
"* + 3 5 / 6 4", "+ 3 5", "+ + 4 1 + + 3 4 + 1 2",
"+ * + 1 2 - 4 2 - 5 2", "+ * / + 1 2 - 3 2 * 2 3 / 3 2"];
for (var i=0; i< tests.length; i++) {
var li = document.createElement("li"), str = tests[i];
li.innerHTML = str + " --> " + evaluate(str);
document.getElementById("results").appendChild(li);
}