-
Notifications
You must be signed in to change notification settings - Fork 0
/
cycle_buffer.js
85 lines (74 loc) · 1.69 KB
/
cycle_buffer.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Cycle buffer that
*/
class CycleBuffer {
constructor(elements, index=0) {
this.elements = elements;
this.index = index;
this.fix_index();
}
next() {
this.index += 1;
this.fix_index();
}
previous() {
this.index -= 1;
this.fix_index();
}
advance_to(index) {
this.index = index;
this.fix_index();
}
fix_index() {
this.index = mod(this.index, this.elements.length);
}
get current() {
return this.elements[this.index];
}
get length() {
return this.elements.length;
}
get_item(index) {
let idx = mod(index, this.elements.length);
return this.elements[idx];
}
/**
* Get all elements with their indices
*
* returns an array of arrays:
* [
* [x1, 0],
* [x2, 1],
* ...
* [xn, n],
* ]
*/
get all() {
return this.elements.map((x, i) => [x, i]);
}
/**
* Find the index of an element with the given id
*/
find_index(id) {
// Linear search, but there's not going to be that many items
// to search through.
let filtered = this.all.filter(([x, i]) => x.id === id);
if (filtered.length < 1) {
return -1;
} else {
let [, idx] = filtered[0];
return idx;
}
}
/**
* like this.all except we exclude the element that matches
* the index
*/
all_except(index) {
let reduced_index = mod(index, this.elements.length);
return this.all.filter(([, i]) => i != reduced_index);
}
map(func) {
return this.elements.map(func);
}
}