summaryrefslogtreecommitdiff
path: root/javascripts/Stack.js
blob: 3349ffb5dfb838d13fc873a2aca74ffbc380d7c5 (plain)
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
/*
 * Stack
 * Simple implementation of a stack using Array().
 */


function Stack() {
	this.a 		= new Array();
	this.length = 0;
};

// Push an item.
Stack.prototype.push = function(obj) {
	this.a.push(obj);
	this.length++;
};

// Pop an item.
Stack.prototype.pop = function() {
	if (this.isEmpty()) {
		throw('Stack.pop(): Pop from empty stack.');
	};
	this.length--;
	return this.a.pop();
};

// Check if stack is empty.
Stack.prototype.isEmpty = function() {
	if (this.length == 0) {
		return true;
	};
	return false;
};

// Get an item at position index.
Stack.prototype.get = function(index) {
	return this.a[index];
};

// Deep copy a stack.
Stack.prototype.copy = function() {
	var c = ((new Array()).concat(this.a));
	var ret = new Stack();
	ret.a = c;
	ret.length = this.length;
	return ret;
};

// String representation.
Stack.prototype.str = function(separator) {
	if (!separator) { separator=' ' };
	var a = new Array();
	for (var i=0; i < this.length; i++) {
		a.push(this.a[i].id);
	};
	return a.join(separator);
};