Skip to content

Instantly share code, notes, and snippets.

@adamvr
Created December 3, 2012 11:39
Show Gist options
  • Save adamvr/4194410 to your computer and use it in GitHub Desktop.
Save adamvr/4194410 to your computer and use it in GitHub Desktop.
Fiddlin
@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');
<div class="container">
<input type="text" name="Calculate" id="expr" value="" />
<a class="btn btn-primary" id="calc" href=""> Calculate </a>
<input type="text" name="Result" id="res" value="" />
</div>
var Stack = function Stack(size) {
this.size = size;
this.stack = new Array(size);
this.head = 0;
}
Stack.prototype.push =
function(element) {
if (this.head > this.size) {
return false;
} else {
this.stack[this.head++] = element;
return true;
}
};
Stack.prototype.pop =
function() {
if (this.this.head < 0) {
return null;
} else {
return this.stack[this.head--];
}
};
Stack.prototype.peek =
function() {
return this.stack[this.head];
};
var Calculator = function Calculator() {
this.stack = new Stack(128)
}
Calculator.prototype.calculate =
function(expression) {
var s = this.stack,
cur = "";
for (var i = 0; i < expression.length; i += 1) {
var c = expression[i];
if (/[0-9]/.test(c)) {
cur += c;
} else if (c === " ") {
s.push(cur | 0);
cur = "";
} else if (/\*\-\/\+/.test(c)) {
var op1 = s.pop(),
op2 = s.pop();
switch (c) {
case '*':
s.push(op1 * op2);
break;
case '/':
s.push(op1 / op2);
break;
case '+':
s.push(op1 + op2);
break;
case '-':
s.push(op1 - op2);
break;
}
} else {
return null
}
}
return s.pop()
};
window.calculator = new Calculator();
window.addEvent('domready', function () {
var expr = $("expr"),
res = $("res"),
calc = $("calc");
calc.addEvent('click', function () {
res.set('value', calculator.calculate(expr.value));
});
});
name: DC
description: Desk calculator
authors:
- Adam Rudd
resources
- http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js
normalize_css: no
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment