-
Notifications
You must be signed in to change notification settings - Fork 1
/
rolling_window.js
79 lines (62 loc) · 2.11 KB
/
rolling_window.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
"use strict";
function rolling_window() {
var window = [];
var window_size = 1;
this.setWindowSize = function (size) {
if (size == undefined) {
throw new Error("size required in this method");
}
if (!isFinite(size)) {
throw new Error("size should be integer number");
}
if ((+size - parseInt(+size)) != 0) {
throw new Error("size should be integer number");
}
window_size = +size;
adjustWindow();
return;
}
this.getWindowSize = function () {
return window_size;
}
this.getWindow = function () {
return window;
}
this.clearWindow = function () {
window = [];
}
this.push = function (item) {
if (item == undefined)
throw new Error("Item required in this method");
window.push(item);
adjustWindow();
return;
}
this.print = function () {
console.log({ windowSize: window_size, window: window });
}
this.reduce = function(reduceMethod, startValue) {
if (reduceMethod == undefined || typeof reduceMethod !== 'function')
throw new Error("a function is required at first argument");
if (startValue == undefined)
throw new Error("startValue(second argument) required in this method");
if (!isFinite(startValue))
throw new Error("startValue(second argument) should be an integer");
if ((+startValue - parseInt(+startValue)) != 0)
throw new Error("startValue(second argument) should be an integer");
startValue = +startValue;
return this.getWindow().reduce(reduceMethod, startValue);
}
this.each = function(eachMethod) {
if (eachMethod == undefined || typeof eachMethod !== 'function')
throw new Error("a function is required at first argument");
return this.getWindow().map(eachMethod);
}
function adjustWindow() {
for (var i = window.length; i > window_size; i--) {
window.shift();
}
}
return this;
}
module.exports = rolling_window;