Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 | 3x 3x 3x 3x 3x 3x 3x 3x 130x 130x 130x 130x 130x 2x 2x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 435x 267x 265x 264x 233x 265x 265x 44x 224x 224x 51x 85x 85x 98x 1x 97x 97x 97x 97x 176x 175x 175x 29x 28x 28x 9x 8x 8x 5x 4x 4x 4x 131x 131x 131x 104x 104x 104x 4x 4x 4x 21x 248x 437x 17x 1x 1x 2x 1x 2x 1x 3x 4x 3x 4x 4x 7x 7x 2x 1x 1x 3x 3x 1x 1x 1x 4x 4x 5x 5x 1x 1x 1x 3x 3x 7x 7x 1x 1x 4x 4x 3x 4x 4x 11x 1x 1x 1x 10x 10x 1x 2x 1x 2x 2x 2x 4x 1x 1x 2x 2x 2x 4x 1x 1x 17x 17x 17x 17x 6x 5x 5x 8x 5x 4x 4x 7x 2x 2x 26x 26x 26x 26x 26x 36x 28x 16x 28x 28x 28x 28x 28x 1x 12x 12x 12x 10x 10x 10x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 1x 2x 2x 9x 9x 7x 7x 1x 2x 1x 1x 1x 10x 5x 5x 2x 2x 2x 14x 14x 1x 1x 6x 6x 1x 1x 10x 10x 1x 3x 3x 3x 6x 6x 4x 4x | import StreamSubscription from "./stream_subscription";
import StreamController from "./stream_controller";
import { StreamSubscriptionActions } from "./stream_subscription";
import {
StreamMessageType,
StreamMessage,
StreamListener,
StreamListenOptions,
StreamCallback,
StreamInterface,
} from "./types";
import {
createDataMessage,
createErrorMessage,
cancelAndFulfill,
nextTick,
createDoneMessage,
} from "./stream_utils";
/**
* Error to be thrown when adding to a closed stream
*/
/** @ignore */
const ErrorForAdd = new Error("cannot add to closed stream");
/**
* Error to be thrown when adding errors to a closed stream
*/
/** @ignore */
const ErrorForAddError = new Error("cannot add error to closed stream");
/**
* Error to be thrown when there are multiple listeners to a non-broadcast stream
*/
/** @ignore */
const ErrorForListen = new Error(
"cannot have more than one listener on the stream"
);
/** @ignore */
type StreamEventsMap = {
[key: string]: Array<StreamCallback>;
};
/**
* Stream
* @template T - the type for the data in the stream
*/
export default class Stream<T> implements StreamInterface<T> {
private _subscription: StreamSubscription<T> | null = null;
/** The buffer containing the stream messages */
private _buffer: Array<StreamMessage<T>> = [];
/** internal flag representing the paused state of the stream */
private _isPaused: boolean = false;
/** internal flag representing the closed state of the stream */
protected _isClosed: boolean = false;
protected _eventCallbacks: StreamEventsMap = {};
/**
* Derive a stream from a promise.
*
* @param promise - The promise to convert to a stream
* @returns Stream - The stream
* @template T - the type of the data resolved by the promise
*/
static fromPromise<T>(promise: Promise<T>): StreamInterface<T> {
const streamController = new StreamController<T>();
promise
.then((value) => {
streamController.add(value);
streamController.close();
})
.catch((e) => {
streamController.addError(e);
streamController.close();
});
return streamController.stream;
}
/**
* Derives a stream from promises
*
* Resolved values are data on the stream. Rejected values are errors on the stream.
* Stream is closed after all promises have been resolved.
* @param promises
* @template T the type of data resolved by the promises
*/
static fromPromises<T>(promises: Iterable<Promise<T>>): StreamInterface<T> {
const streamController = new StreamController<T>();
let count = 0;
const onData = (data: T) => {
Eif (!streamController.isClosed) {
streamController.add(data);
Iif (--count === 0) streamController.close();
}
};
const onError = (error: Error) => {
Eif (!streamController.isClosed) {
streamController.addError(error);
Eif (--count === 0) streamController.close();
}
};
for (let p of promises) {
count++;
p.then(onData, onError);
}
return streamController.stream;
}
/**
* Derives a new stream from an existing stream.
*
* @param stream
* @returns stream
* @template T the type of the data in the stream
*/
static fromStream<T>(stream: Stream<T>): StreamInterface<T> {
return new _filteringStream(stream);
}
/**
* _emit - emit messages to listeners
*/
/** @ignore */
private _emit() {
if (this.isPaused || !this._subscription) return;
nextTick(() => {
this._buffer.forEach((message) => {
if (this._subscription) {
this._subscription.messageHandler(message);
}
});
this._buffer = [];
if (this._isClosed && this._subscription) {
this.cancel(this._subscription);
}
});
}
/**
* Fire callbacks for event listeners
*
* @param name - the event name
*/
protected _callEventListeners(name: string) {
nextTick(() => {
if (this._eventCallbacks[name] && this._eventCallbacks[name].length) {
this._eventCallbacks[name].forEach((c) => c());
}
});
}
/**
* Cancel a StreamSubscription
*
* This is called when StreamSubscription.cancel() is called.
*/
cancel(_: StreamSubscription<T>) {
this._subscription = null;
this._callEventListeners("onCancel");
}
/**
* Subscribes a listener and callbacks to the stream.
*
* Override to alter the behavior on how listeners are managed.
* @param onData - the listener
* @param callbacks - the optional error and ondone callbacks
*/
listen(
onData: StreamListener<T>,
callbacks: StreamListenOptions = {}
): StreamSubscriptionActions {
if (this._subscription) {
throw ErrorForListen;
}
this._subscription = new StreamSubscription(this, onData, callbacks);
this._callEventListeners("onListen");
this._emit();
return this._subscription;
}
/**
* Add messages to the stream.
*
* Override to alter how data is processed
* @param data - the data to add
*/
add(data: T) {
if (this.isClosed) throw ErrorForAdd;
this._buffer.push(createDataMessage(data));
this._emit();
}
/**
* Add errors to the stream.
*
* Override to alter how errors are processed
* @param message - the error or error message
*/
addError(message: string | Error) {
if (this.isClosed) throw ErrorForAddError;
this._buffer.push(createErrorMessage(message));
this._emit();
}
/**
* Pause the stream.
*
* When a stream is paused, listeners are no longer notified for incoming messages.
* Unless the stream is a broadcast stream, messages are buffered until the stream is resumed.
*/
pause() {
if (!this._isPaused) {
this._isPaused = true;
this._callEventListeners("onPause");
}
}
/**
* Resume the stream.
*
* Unless the stream is a broadcast stream, buffered messages will be
* dispatched to listeners when the stream resumes.
*/
resume() {
if (this._isPaused) {
this._isPaused = false;
this._callEventListeners("onResume");
this._emit();
}
}
/**
* Close the stream.
*
* When a stream is closed, add messages/errors to the stream are then prohibbited.
*/
close() {
this._isClosed = true;
this._buffer.push(createDoneMessage());
this._emit();
}
/**
* Add an event listener to the stream.
*
* This is used to be notified for events such as:
* onListen, onPause, onResume, onCancel.
*
* @param name - the name of the event
* @param callback
*/
addEventListener(name: string, callback: StreamCallback) {
Eif (!this._eventCallbacks[name]) {
this._eventCallbacks[name] = [];
}
this._eventCallbacks[name].push(callback);
}
/**
* Remove an event listener from the stream.
*
* @param name - the name of the event
* @param callback
*/
removeEventListener(name: string, callback: StreamCallback) {
Iif (!this._eventCallbacks[name]) return;
this._eventCallbacks[name] = this._eventCallbacks[name].filter(
(c) => c !== callback
);
}
/**
* Whether the stream is a broadcast stream
*/
get isBroadcast() {
return false;
}
/**
* The **closed** state of the stream.
*
* @return boolean
*/
get isClosed() {
return this._isClosed;
}
/**
* The **paused** state of the stream.
*
* @returns boolean
*/
get isPaused() {
return this._isPaused;
}
/**
* asBroadcastStream
*
* Creates a multilistener enabled stream that receives messages from the current stream.
* The broadcast stream subscribes to the current stream when it receives its first listener.
*/
asBroadcastStream(): StreamInterface<T> {
return new _broadcastStream(this);
}
/**
* Derives new stream that emits mapped values.
*
* @param transform - the function that maps data of type T => type U
* @template T original data type
* @template U new data type
*/
map(transform: (data: T) => any): StreamInterface<T> {
return new _mapStream<T, any>(this, transform);
}
/**
* Derives new stream that consumes only the first *n* messages of the current stream.
*
* @param n - the number of messages to consume
*/
take(n: number): StreamInterface<T> {
return new _takeStream(this, n);
}
/**
* Dervices a new stream that continues to receive messages from the current stream
* as long as the `condition` function returns true.
*
* @param condition - function that returns true to continue taking
*/
takeWhile(condition: (data: T) => boolean): StreamInterface<T> {
return new _takeWhileStream(this, condition);
}
/**
* Derives new stream that skips the first *n* messages of the current stream.
*
* @param n - the number of messages to skip
*/
skip(n: number): StreamInterface<T> {
return new _skipStream(this, n);
}
/**
* Derives new stream that continues to skip elements in the parent stream
* until the `condition` function returns false.
*
* @param condition
*/
skipWhile(condition: (data: T) => boolean): StreamInterface<T> {
return new _skipWhileStream(this, condition);
}
/**
* Derives new stream that only receives messages from the parent stream if
* the message matches the condition.
*
* @param condition
*/
where(condition: (data: T) => boolean): StreamInterface<T> {
return new _whereStream(this, condition);
}
/**
* Derives new stream that only passes data from the parent stream if the data does not equal
* the previously passed data.
*
* @param equals - function that checks if two values are the same
*/
distinct(equals?: (oldVal: T|null, newVal: T|null) => boolean): StreamInterface<T> {
if (!equals) {
equals = (oldVal, newVal) => oldVal === newVal;
}
return new _distinctStream(this, equals);
}
/**
* Checks if every message in the stream satisfies a certain condition
*
* @param condition
* @returns Promise - Resolved if every message satifies the condtion, Rejects otherwise
*/
every(condition: (data: T) => boolean): Promise<boolean> {
return new Promise((resolve, reject) => {
const sub = this.listen(
(data) => {
try {
if (condition(data)) return;
} catch (_) {}
cancelAndFulfill(false, sub, reject);
},
{
onError: (e) => cancelAndFulfill(e, sub, reject),
onDone: () => resolve(true),
}
);
});
}
/**
* first - gets the first element in the stream
*
* Resolves the first element on the stream.
* Rejects if there is an error before the first element is found.
* Rejects if the stream is empty.
*
* @returns Promise
*/
first(): Promise<T> {
return new Promise((resolve, reject) => {
const sub = this.listen(
(data) => {
cancelAndFulfill(data, sub, resolve);
},
{
onError: (e) => cancelAndFulfill(e, sub, reject),
onDone: () => reject(new Error()),
}
);
});
}
/**
* firstWhere - gets the first element on the stream that matches a condition
*
* Resolves the first element that meets the condition.
* Rejects if there is an error before the first element is found.
* Rejects if the stream is empty.
*
* @param condition
*/
firstWhere(condition: (data: T) => boolean): Promise<T> {
return new Promise((resolve, reject) => {
const sub = this.listen(
(data: T) => {
try {
if (condition(data)) return cancelAndFulfill(data, sub, resolve);
} catch (e) {
cancelAndFulfill(e, sub, reject);
}
},
{
onError: (e) => cancelAndFulfill(e, sub, reject),
onDone: () => cancelAndFulfill(null, sub, reject),
}
);
});
}
/**
* forEach - calls the callback for each element in the stream
*
* @param listener
* @returns Promise - Resolved when the stream has ended, Rejected on error.
*/
forEach(listener: StreamListener<T>): Promise<void> {
return new Promise<void>((resolve, reject) => {
const sub = this.listen(
(data) => {
try {
listener(data);
} catch (e) {
cancelAndFulfill(e, sub, reject);
}
},
{
onDone: resolve,
onError: (e) => cancelAndFulfill(e, sub, reject),
}
);
});
}
/**
* Calls a reducer function and returns value from the final call.
*
* @param reducer - fn that returns the new value by taking previous and current messages
* @param initialValue - the initial value
*/
reduce(
reducer: (prev: any, next: T) => any,
initialValue?: any
): Promise<any> {
let seenFirst = false;
if (initialValue !== undefined) {
seenFirst = true;
}
return new Promise((resolve, reject) => {
const sub = this.listen(
(item) => {
if (!seenFirst) {
initialValue = item;
seenFirst = true;
return;
}
try {
initialValue = reducer(initialValue, item);
} catch (e) {
cancelAndFulfill(e, sub, reject);
}
},
{
onDone: () => resolve(initialValue),
onError: (e) => cancelAndFulfill(e, sub, reject),
}
);
});
}
/**
* Takes the elements of a stream and outputs it into an Array.
*
* Note: if the stream outputs an error, the promise rejects with the error
* from the stream.
*
* @returns Promise
*/
toArray(): Promise<Array<T>> {
return new Promise<Array<T>>((resolve, reject) => {
const result: Array<T> = [];
const sub = this.listen(
(data: T) => {
result.push(data);
},
{
onError: (e) => cancelAndFulfill(e, sub, reject),
onDone: () => resolve(result),
}
);
});
}
/**
* Takes the elements of a stream and outputs it into a Set.
*
* Note: if the stream outputs an error, the partial result will be
* provided in the reject of the promise.
* @returns Set
*/
toSet(): Promise<Set<T>> {
return new Promise<Set<T>>((resolve, reject) => {
const result: Set<T> = new Set();
const sub = this.listen(
(data: T) => {
result.add(data);
},
{
onError: (e) => cancelAndFulfill(e, sub, reject),
onDone: () => resolve(result),
}
);
});
}
}
/** @ignore */
class _broadcastStream<T> extends Stream<T> {
private _parentSubscription: StreamSubscriptionActions | null = null;
private _subscribers: Set<StreamSubscription<T>> = new Set();
constructor(private parent: Stream<T>) {
super();
}
add(data: T) {
if (this.isClosed) throw ErrorForAdd;
const message = createDataMessage(data);
nextTick(() => {
this._subscribers.forEach((s) => s.messageHandler(message));
});
}
addError(e: string | Error) {
if (this.isClosed) throw ErrorForAddError;
const error = createErrorMessage(e);
nextTick(() => {
this._subscribers.forEach((s) => s.messageHandler(error));
});
}
cancel(subscription: StreamSubscription<T>) {
this._subscribers.delete(subscription);
this._callEventListeners("onCancel");
}
pause() {}
resume() {}
close() {
this._isClosed = true;
this._parentSubscription?.cancel();
this._parentSubscription = null;
nextTick(() => {
this._subscribers.forEach((s) => {
s.messageHandler({ type: StreamMessageType.Done });
});
});
}
listen(
onData: StreamListener<T>,
callbacks: StreamListenOptions = {}
): StreamSubscriptionActions {
if (!this._parentSubscription) {
this._parentSubscription = this.parent.listen(this.add.bind(this), {
onError: this.addError.bind(this),
onDone: this.close.bind(this),
});
}
const sub = new StreamSubscription(this, onData, callbacks);
this._subscribers.add(sub);
this._callEventListeners("onListen");
if (this.isClosed) this.close();
return sub;
}
get isBroadcast() {
return true;
}
}
/** @ignore */
class _filteringStream extends Stream<any> {
protected _sub: StreamSubscriptionActions | null = null;
constructor(private parent: Stream<any>) {
super();
}
close() {
this._sub?.cancel();
this._sub = null;
super.close();
}
listen(
onData: StreamListener<any>,
callbacks: StreamListenOptions = {}
): StreamSubscriptionActions {
Eif (!this._sub) {
this._sub = this.parent.listen(this.add.bind(this), {
onError: this.addError.bind(this),
onDone: this.close.bind(this),
});
}
return super.listen(onData, callbacks);
}
}
/** @ignore */
class _mapStream<T, U> extends _filteringStream {
constructor(parent: Stream<T>, private transform: (data: T) => U) {
super(parent);
}
add(data: T) {
const newData = this.transform(data);
super.add(newData);
}
}
/** @ignore */
class _takeStream<T> extends _filteringStream {
private _taken: number = 0;
constructor(parent: Stream<T>, private takeAmount: number) {
super(parent);
}
add(data: T) {
Eif (this._taken < this.takeAmount) {
super.add(data);
this._taken++;
}
if (this._taken >= this.takeAmount) {
this.close();
}
}
}
/** @ignore */
class _takeWhileStream<T> extends _filteringStream {
constructor(s: Stream<T>, private condition: (data: T) => boolean) {
super(s);
}
add(data: T) {
try {
if (this.condition(data)) {
super.add(data);
return;
}
} catch (e) {
super.addError(e);
}
this.close();
}
}
/** @ignore */
class _skipStream<T> extends _filteringStream {
private _skipped: number = 0;
constructor(parent: Stream<T>, private skipAmount: number) {
super(parent);
}
add(data: T) {
if (this._skipped < this.skipAmount) {
return this._skipped++;
}
super.add(data);
}
}
/** @ignore */
class _skipWhileStream<T> extends _filteringStream {
private _isSkipping: boolean = true;
constructor(parent: Stream<T>, private condition: (data: T) => boolean) {
super(parent);
}
add(data: T) {
try {
if (this._isSkipping && this.condition(data)) return;
} catch (e) {
this._isSkipping = false;
return super.addError(e);
}
this._isSkipping = false;
super.add(data);
}
}
/** @ignore */
class _whereStream<T> extends _filteringStream {
/**
* whereStream constructor
* @param parent - the parent stream
* @param condition - the function that returns true for messages to keep
*/
constructor(parent: Stream<T>, private condition: (data: T) => boolean) {
super(parent);
}
add(data: T) {
try {
if (this.condition(data)) {
super.add(data);
}
} catch(e) {
super.addError(e);
}
}
}
/** @ignore **/
class _distinctStream<T> extends _filteringStream {
private _oldVal: T | null = null;
/**
* distinctStream constructor
* @param parent - the parent stream
* @param equals - the function that tests if two values are equal
*/
constructor(parent: Stream<T>, private equals: (oldVal: T|null, newVal: T|null) => boolean) {
super(parent);
}
add(data: T) {
try {
if (!this.equals(this._oldVal, data)) {
this._oldVal = data
super.add(data);
}
} catch(e) {
super.addError(e);
}
}
}
|