forked from benjaminplee/QuickPiet
/
commands.js
executable file
·62 lines (49 loc) · 1.37 KB
/
commands.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Commands = {
push : function(stack, args) {
if(!args || args.length == 0 || args.match(/[^0-9\s]/)) {
throw new SyntaxError("Invalid PUSH argument(s)")
}
jQuery.each(args.split(' '), function(index, value) {
stack.push(parseInt(value))
})
},
pop : function(stack, args) {
var pops_count = 1
if(args && args.length > 0) {
args = jQuery.trim(args)
if(args.length == 0 || args.match(/[^0-9\s]/) || parseInt(args) == NaN) {
throw new SyntaxError('Invalid POP argument(s)')
}
else {
pops_count = parseInt(args)
}
}
if(pops_count > stack.length) {
throw new EvalError('Can not POP from empty stack')
}
for(var i = 0; i < pops_count; i++) {
stack.pop()
}
},
duplicate : function(stack) {
this._enforce_non_empty_stack(stack, 'DUPLICATE')
var val = stack.pop()
stack.push(val)
stack.push(val)
},
add : function(stack) {
this._enforce_non_empty_stack(stack, 'ADD')
stack.push(stack.pop() + stack.pop())
},
subtract : function(stack) {
this._enforce_non_empty_stack(stack, 'SUBTRACT')
var top = stack.pop()
var second_top = stack.pop()
stack.push(second_top - top)
},
_enforce_non_empty_stack : function(stack, method_name) {
if(stack.length == 0) {
throw new EvalError('Can not ' + method_name + ' from empty stack')
}
}
}