diff options
Diffstat (limited to 'ui/lib/iterator.js')
| -rw-r--r-- | ui/lib/iterator.js | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/ui/lib/iterator.js b/ui/lib/iterator.js new file mode 100644 index 0000000..1d6a740 --- /dev/null +++ b/ui/lib/iterator.js @@ -0,0 +1,35 @@ +export function* map(xs, fn) { + for (const x of xs) { + yield fn(x); + } +} + +export function reduce(xs, fn, initial) { + let value = initial; + for (const x of xs) { + value = fn(value, x); + } + return value; +} + +export function* chunkBy(xs, keyFn, coalesceFn) { + let chunk; + let key; + for (const x of xs) { + const newKey = keyFn(x); + + if (key === undefined) { + chunk = [x]; + } else if (coalesceFn(key, newKey)) { + chunk.push(x); + } else { + yield { key, chunk }; + + chunk = [x]; + } + key = newKey; + } + if (chunk !== undefined) { + yield { key, chunk }; + } +} |
