-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_array.js
More file actions
93 lines (84 loc) · 2.7 KB
/
Copy pathdemo_array.js
File metadata and controls
93 lines (84 loc) · 2.7 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function DemoArray(size, presentor)
{
this.array = new Array(size);
this.length = size;
this.fetched = null;
this.fetched_index = null;
presentor = presentor || {};
var default_presentor = {
set: function(index, value){},
fetched: function(from_index, value){},
unfetched: function(to_index) {},
before_compare: function(index_a, index_b){},
compared: function(index){},
moved: function(from, to, from_value, to_value) {}
};
this.presentor = jQuery.extend(default_presentor, presentor);
};
DemoArray.prototype = {
randomize: function(max_value) {
for(var j=0; j< this.array.length; j++) {
this.array[j] = Math.floor(Math.random()*(max_value + 1));
this.presentor.set(j, this.array[j]);
}
},
fetch: function(index, replacement) {
if(this.fetched) {
throw "There is already a fetched element"
}
var replacement_value = (arguments.length == 2 ? replacement : null);
// insert replacement value in index
this.fetched = this.array.splice(index, 1, replacement_value)[0];
this.fetched_index = index;
this.presentor.fetched(index, this.fetched);
this.presentor.set(index, this.array[index]);
return(this.fetched);
},
at: function(index) {
return (this.array[index]);
},
set: function(index, value) {
this.array[index] = value;
this.presentor.set(index, value);
},
move: function(from, to) {
var previous_to = this.array[to];
// If from is -1, use fetched value
this.array[to] = from >=0 ? this.array[from] : this.fetched;
this.array[from] = null;
this.presentor.moved(from, to, this.array[from], this.array[to]);
return (previous_to);
},
swap: function(index_a, index_b) {
var value_a = this.at(index_a);
var value_b = this.at(index_b);
this.array[index_b] = value_a;
this.array[index_a] = value_b;
this.presentor.set(index_a, value_b);
this.presentor.set(index_b, value_a);
},
unfetch: function(to) {
if(this.fetched == null) {
throw "No fetched element, can not unfetch"
}
var previous_to = this.move(-1, to);
this.fetched = this.fetched_index = null; // reset
this.presentor.unfetched(to);
return(previous_to);
},
compare: function(a, b) {
var val_a = this.array[a];
//var val_b = (b instanceof Object ? b.val: this.array[b]);
var val_b = (b == -1 ? this.fetched : this.array[b]);
this.presentor.before_compare(a, b);
var index_of_larger;
if(val_a < val_b)
index_of_larger = b;
if(val_a == val_b)
index_of_larger = null;
if(val_a > val_b)
index_of_larger = a;
this.presentor.compared(index_of_larger);
return(index_of_larger);
}
}