Mithril v2 streams should have a generalized fold
.
#2932
Replies: 1 comment
-
Okay, so here's my latest idea: a // function groupBy<T, K>(s: Stream<T>, k: (v: T) => K): Stream<[K, Stream<T>]>
function groupBy(s, func) {
const acc = new Map()
return s.transform(t => v => {
if (v === Stream.SKIP) {
t(Array.from(acc))
t.end(true)
} else {
const key = func(v)
const target = acc.get(key)
if (target != null) target(v)
else acc.set(key, Stream(v))
}
})
}
// function take<T>(s: Stream<T>, n: number): Stream<T>
function take(s, n) {
if (!n) { const t = Stream(); t.end(true); return t }
return s.transform(t => v => {
if (v === Stream.SKIP) return t.end(true)
t(v)
if (!--n) t.end(true)
})
}
// function drop<T>(s: Stream<T>, n: number): Stream<T>
function drop(s, n) {
return !n ? s : s.transform(t => v => {
if (v === Stream.SKIP) t.end(true)
else if (n) n--
else t(v)
})
}
// function reduce<T, U>(s: Stream<T>, f: (v: T) => U): Stream<U>
function reduce(s, func, init) {
return s.transform(t => v => {
if (v === Stream.SKIP) { t(init); t.end(true) }
else init = func(init)
})
} Yes, this is similar to RxJS's |
Beta Was this translation helpful? Give feedback.
-
Description
Something like this, where the stream doesn't emit immediately, but correctly and performantly handles folds:
This would, for the most part, act like
sourceStream.map(func)
, but with the following difference: when the source stream ends, the callback is called once more withvalue
set toStream.SKIP
to get the final emit. (This is convenient for some pass-throughs, as one example shows below, and is currently impossible to receive.)Why
There's several userland helpers where this could simplify a lot and make it a lot easier to properly handle closure. For instance:
In each case,
Stream.scan
is not sufficient, and they really need that fused with a conceptualreduce
operation, and that's the basic functionality this fills.Possible Implementation & Open Questions
Here's a basic (untested) userland implementation of it:
Of course, this would be way easier to do with access to internal state.
Open questions:
Is this something you're interested in working on?
Yes. This is not a v2 blocker, however.
Beta Was this translation helpful? Give feedback.
All reactions