File size: 2,030 Bytes
96af7c9 |
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 80 81 82 83 84 85 86 87 |
import { filterHelper, flatMapHelper, joinHelper, mapHelper, nilHelper, takeNHelper, takeWhileHelper, } from './StreamHelpers.js';
const safeSymbolIterator = Symbol.iterator;
export class Stream {
static nil() {
return new Stream(nilHelper());
}
static of(...elements) {
return new Stream(elements[safeSymbolIterator]());
}
constructor(g) {
this.g = g;
}
next() {
return this.g.next();
}
[Symbol.iterator]() {
return this.g;
}
map(f) {
return new Stream(mapHelper(this.g, f));
}
flatMap(f) {
return new Stream(flatMapHelper(this.g, f));
}
dropWhile(f) {
let foundEligible = false;
function* helper(v) {
if (foundEligible || !f(v)) {
foundEligible = true;
yield v;
}
}
return this.flatMap(helper);
}
drop(n) {
if (n <= 0) {
return this;
}
let idx = 0;
function helper() {
return idx++ < n;
}
return this.dropWhile(helper);
}
takeWhile(f) {
return new Stream(takeWhileHelper(this.g, f));
}
take(n) {
return new Stream(takeNHelper(this.g, n));
}
filter(f) {
return new Stream(filterHelper(this.g, f));
}
every(f) {
for (const v of this.g) {
if (!f(v)) {
return false;
}
}
return true;
}
has(f) {
for (const v of this.g) {
if (f(v)) {
return [true, v];
}
}
return [false, null];
}
join(...others) {
return new Stream(joinHelper(this.g, others));
}
getNthOrLast(nth) {
let remaining = nth;
let last = null;
for (const v of this.g) {
if (remaining-- === 0)
return v;
last = v;
}
return last;
}
}
export function stream(g) {
return new Stream(g);
}
|