Repository navigation
Expand file tree
/
Copy pathexample.js
More file actions
97 lines (79 loc) · 1.94 KB
/
Copy pathexample.js
File metadata and controls
97 lines (79 loc) · 1.94 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
94
95
96
97
function CircularBuffer(capacity) {
var readPoint = 0;
var writePoint = 0;
var buffer = new Array(capacity);
return {
read: function () {
if (isBufferEmpty()) { throw new BufferEmptyException(); }
var data = buffer[readPoint];
buffer[readPoint] = null;
updateReadPoint();
return data;
},
write: function (data) {
updateBuffer(data, function () {
if (isBufferFull()) { throw new BufferFullException(); }
buffer[writePoint] = data;
});
},
forceWrite: function (data) {
updateBuffer(data, function () {
if (isBufferFull()) { updateReadPoint(); }
buffer[writePoint] = data;
});
},
clear: function () {
readPoint = 0;
writePoint = 0;
buffer = new Array(capacity);
},
isFull: function () {
return isBufferFull();
},
isEmpty: function () {
return isBufferEmpty();
}
};
function isBufferEmpty() {
return buffer.every(isEmpty);
}
function isBufferFull() {
return buffer.filter(isFull).length === capacity;
}
function updateBuffer(data, callback) {
if (isEmpty(data)) { return; }
callback();
updateWritePoint();
}
function updateWritePoint() {
writePoint = (writePoint + 1) % capacity;
}
function updateReadPoint() {
readPoint = (readPoint + 1) % capacity;
}
function isFull(data) {
return !isEmpty(data);
}
function isEmpty(data) {
return !data;
}
}
function BufferEmptyException() {
this.name = 'BufferEmptyException';
this.message = 'Buffer is empty.';
}
function BufferFullException() {
this.name = 'BufferFullException';
this.message = 'Buffer is full.';
}
module.exports = {
circularBuffer: function (capacity) {
return new CircularBuffer(capacity);
},
bufferEmptyException: function () {
return new BufferEmptyException();
},
bufferFullException: function () {
return new BufferFullException();
}
};