Skip to content

Commit 6f10b74

Browse files
authored
add first and last reducers for window (#636)
1 parent 7ebba6c commit 6f10b74

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1463,6 +1463,8 @@ The following window reducers are supported:
14631463
* *variance* - the variance per [Welford’s algorithm](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm)
14641464
* *difference* - the difference between the last and first window value
14651465
* *ratio* - the ratio of the last and first window value
1466+
* *first* - the first value
1467+
* *last* - the last value
14661468
* a function to be passed an array of *k* values
14671469

14681470
By default, **anchor** is *middle* and **reduce** is *mean*.

src/transforms/window.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ function maybeReduce(reduce = "mean") {
5151
case "variance": return reduceSubarray(variance);
5252
case "difference": return reduceDifference;
5353
case "ratio": return reduceRatio;
54+
case "first": return reduceFirst;
55+
case "last": return reduceLast;
5456
}
5557
}
5658
if (typeof reduce !== "function") throw new Error("invalid reduce");
@@ -130,3 +132,23 @@ function reduceRatio(k, s) {
130132
}
131133
};
132134
}
135+
136+
function reduceFirst(k, s) {
137+
return {
138+
map(I, S, T) {
139+
for (let i = 0, n = I.length - k; i < n; ++i) {
140+
T[I[i + s]] = S[I[i]];
141+
}
142+
}
143+
};
144+
}
145+
146+
function reduceLast(k, s) {
147+
return {
148+
map(I, S, T) {
149+
for (let i = 0, n = I.length - k; i < n; ++i) {
150+
T[I[i + s]] = S[I[i + k - 1]];
151+
}
152+
}
153+
};
154+
}

0 commit comments

Comments
 (0)