-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0900-rle-iterator.js
More file actions
44 lines (39 loc) · 1.17 KB
/
0900-rle-iterator.js
File metadata and controls
44 lines (39 loc) · 1.17 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
/**
* Rle Iterator
* Time Complexity: O(L)
* Space Complexity: O(L)
*/
var RLEIterator = function (encoding) {
this.rleRecords = [];
this.currentRecordIndex = 0;
this.consumedFromCurrent = 0;
for (let recordIndex = 0; recordIndex < encoding.length; recordIndex += 2) {
let frequencyOfValue = encoding[recordIndex];
let actualValue = encoding[recordIndex + 1];
if (frequencyOfValue > 0) {
this.rleRecords.push([frequencyOfValue, actualValue]);
}
}
};
RLEIterator.prototype.next = function (n) {
let elementsRemaining = n;
while (
this.currentRecordIndex < this.rleRecords.length &&
elementsRemaining > 0
) {
let recordData = this.rleRecords[this.currentRecordIndex];
let totalFrequency = recordData[0];
let actualValueResult = recordData[1];
let currentlyAvailable = totalFrequency - this.consumedFromCurrent;
if (elementsRemaining > currentlyAvailable) {
elementsRemaining -= currentlyAvailable;
this.consumedFromCurrent = 0;
this.currentRecordIndex++;
} else {
this.consumedFromCurrent += elementsRemaining;
elementsRemaining = 0;
return actualValueResult;
}
}
return -1;
};