-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
518 lines (400 loc) · 11.3 KB
/
index.ts
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
// An implementation of the Observable proposal.
import { executeSubscriber } from "./execute-subscriber.js"
import { getAsyncIterator } from "./get-async-iterator.js"
import { getIterator } from "./get-iterator.js"
import { getMethod } from "./get-method.js"
import { hostReportError } from "./host-report-error.js"
import { throwTypeError } from "./throw-type-error.js"
;(Symbol as any).observable = Symbol.observable || Symbol("Symbol.observable")
export interface Observer<in T> {
start?(this: this, subscription: Subscription): void
next?(this: this, value: T): void
error?(this: this, reason: unknown): void
complete?(this: this, value: unknown): void
}
export type SubscriberFunction<out T> = (
this: void,
observer: SubscriptionObserver<T>,
) => void | (() => void) | Subscription
export type ObservableLike<T> =
| { [Symbol.observable](): Observable<T> }
| { [Symbol.iterator](): Iterator<T> }
| {
[Symbol.asyncIterator]():
| AsyncIterator<T | PromiseLike<T>>
| Iterator<T | PromiseLike<T>>
}
export class Observable<out T> {
static from<T>(x: ObservableLike<T>): Observable<T> {
let C = this
if (typeof C != "function") {
C = Observable
}
const observableMethod = getMethod(x, Symbol.observable)
if (observableMethod) {
const observable = observableMethod.call(x)
if (
(typeof observable != "object" && typeof observable != "function") ||
!observable
) {
throwTypeError("object", observable)
}
if (observable.constructor === C) {
return observable
}
return new C((observer) => observable.subscribe(observer))
} else if (Symbol.iterator in x) {
const iterator = getIterator<T>(x)
const iterable = { [Symbol.iterator]: () => iterator }
return new C((observer) => {
for (const item of iterable) {
observer.next(item)
}
observer.complete(undefined)
})
} else if (Symbol.asyncIterator in x) {
const iterator = getAsyncIterator<T>(x)
const iterable = { [Symbol.asyncIterator]: () => iterator }
return new C((observer) => {
;(async () => {
for await (const item of iterable) {
observer.next(item)
}
observer.complete(undefined)
})()
})
}
throwTypeError("observable, iterator, or async iterator", x)
}
static of<T>(...items: readonly T[]): Observable<T> {
let C = this
if (typeof C != "function") {
C = Observable
}
return new C((observer: SubscriptionObserver<T>) => {
for (const element of items) {
observer.next(element)
}
observer.complete(undefined)
})
}
readonly #subscriber: SubscriberFunction<T>
constructor(subscriber: SubscriberFunction<T>) {
if (typeof subscriber != "function") {
throwTypeError("function", subscriber)
}
this.#subscriber = subscriber
}
subscribe(observer: Observer<T>): Subscription
subscribe(
onNext: (value: T) => void,
onError?: (reason: unknown) => void,
onComplete?: (value: unknown) => void,
): Subscription
subscribe(
observer: Observer<T> | ((value: T) => void),
onError: ((reason: unknown) => void) | undefined = undefined,
onComplete: ((value: unknown) => void) | undefined = undefined,
): Subscription {
const O = this
if (!(#subscriber in O)) {
throwTypeError("Observer", O)
}
if (typeof observer == "function") {
observer = {
next: observer,
error: onError,
complete: onComplete,
}
} else if (typeof observer != "object" || !observer) {
throwTypeError("observer or function", observer)
}
const subscription = new Subscription(observer)
try {
var start = getMethod(observer, "start")
} catch (error) {
hostReportError(error)
}
if (typeof start != "undefined") {
if (typeof start != "function") {
throwTypeError("function", start)
}
try {
start.call(observer, subscription)
} catch (error) {
hostReportError(error)
}
if (subscription.closed) {
return subscription
}
}
const subscriptionObserver = new SubscriptionObserver(subscription)
const subscriber = O.#subscriber
try {
var subscriberResult = executeSubscriber(subscriber, subscriptionObserver)
} catch (error) {
subscriptionObserver.error(error)
}
setSubscriptionCleanup(subscription, subscriberResult)
if (subscription.closed) {
cleanupSubscription(subscription)
}
return subscription
}
[Symbol.observable](): this {
return this
}
map<U>(mapFn: (value: T) => U): Observable<U> {
return new Observable<U>((observer) => {
return this.subscribe({
next(value) {
observer.next(mapFn(value))
},
error(reason) {
observer.error(reason)
},
complete(value) {
observer.complete(value)
},
})
})
}
flatMap<U>(mapFn: (value: T) => ObservableLike<U>): Observable<U> {
const self = this
return Observable.from(
(async function* () {
for await (const value of self) {
yield* Observable.from(mapFn(value))
}
})(),
)
}
filter<U extends T>(filterFn: (value: T) => value is U): Observable<U>
filter(filterFn: (value: T) => boolean): Observable<T>
filter(filterFn: (value: T) => boolean): Observable<T> {
return new Observable<T>((observer) => {
return this.subscribe({
next(value) {
if (filterFn(value)) {
observer.next(value)
}
},
error(reason) {
observer.error(reason)
},
complete(value) {
observer.complete(value)
},
})
})
}
every(checkFn: (value: T) => boolean): Promise<boolean> {
return (async () => {
for await (const value of this) {
if (!checkFn(value)) {
return false
}
}
return true
})()
}
some(checkFn: (value: T) => boolean): Promise<boolean> {
return (async () => {
for await (const value of this) {
if (checkFn(value)) {
return true
}
}
return false
})()
}
take(maxValues: number): Observable<T> {
return new Observable((observer) => {
let sent = 0
var subscription = this.subscribe({
next(value) {
sent++
if (sent >= maxValues) {
subscription?.unsubscribe()
if (sent != maxValues) {
return
}
}
observer.next(value)
},
error(reason) {
observer.error(reason)
},
complete(value) {
observer.complete(value)
},
})
})
}
async *[Symbol.asyncIterator](): AsyncGenerator<T> {
let wake = () => {}
const queued: T[] = []
let didError = false
let errorValue: unknown
let didComplete = false
let completeValue: unknown
this.subscribe({
next(value) {
if (didError || didComplete) return
queued.push(value)
wake()
},
error(reason) {
if (didError || didComplete) return
didError = true
errorValue = reason
wake()
},
complete(value) {
if (didError || didComplete) return
didComplete = true
completeValue = value
wake()
},
})
while (true) {
yield* queued satisfies T[] as any
queued.length = 0
if (didError) {
throw errorValue
}
if (didComplete) {
return completeValue
}
await new Promise<void>((resolve) => (wake = resolve))
}
}
}
let setSubscriptionCleanup: (
value: Subscription,
cleanup: (() => void) | undefined,
) => void
let cleanupSubscription: (subscription: Subscription) => void
let getSubscriptionObserver: (
subscription: Subscription,
) => Observer<unknown> | undefined
export class Subscription {
static {
setSubscriptionCleanup = (value, cleanup) => {
value.#cleanup = cleanup
}
cleanupSubscription = (subscription) => {
const cleanup = subscription.#cleanup
if (typeof cleanup == "undefined") {
return undefined
}
if (typeof cleanup != "function") {
throwTypeError("function", cleanup)
}
subscription.#cleanup = undefined
try {
cleanup()
} catch (error) {
// If result is an abrupt completion, perform HostReportErrors(« result.[[Value]] »).
hostReportError(error)
}
}
getSubscriptionObserver = (subscription) => {
return subscription.#observer
}
this.prototype.constructor = Object
}
#observer: Observer<unknown> | undefined
#cleanup: (() => void) | undefined
constructor(observer: Observer<any>) {
this.#observer = observer
}
get closed(): boolean {
const subscription = this
if (!(#observer in subscription)) {
throwTypeError("Subscription", subscription)
}
return typeof subscription.#observer == "undefined"
}
unsubscribe(): void {
const subscription = this
if (!(#observer in subscription)) {
throwTypeError("Subscription", subscription)
}
if (subscription.closed) {
return undefined
}
subscription.#observer = undefined
cleanupSubscription(subscription)
}
}
export class SubscriptionObserver<in T> {
#subscription: Subscription
static {
this.prototype.constructor = Object
}
constructor(subscription: Subscription) {
this.#subscription = subscription
}
get closed(): boolean {
const O = this
if (!(#subscription in O)) {
throwTypeError("SubscriptionObserver", O)
}
const subscription = O.#subscription
return subscription.closed
}
next(value: T): void {
const O = this
if (!(#subscription in O)) {
throwTypeError("SubscriptionObserver", O)
}
const subscription = O.#subscription
if (subscription.closed) {
return undefined
}
const observer = getSubscriptionObserver(subscription)!
const nextMethod = getMethod(observer, "next")
if (typeof nextMethod != "undefined") {
if (typeof nextMethod != "function") {
throwTypeError("function", nextMethod)
}
try {
return nextMethod.call(observer, value)
} catch (error) {
subscription.unsubscribe()
throw error
}
}
}
error(exception: unknown): void {
const subscription = this.#subscription
if (subscription.closed) {
throw exception
}
const observer = getSubscriptionObserver(subscription)!
subscription.unsubscribe()
const errorMethod = getMethod(observer, "error")
if (typeof errorMethod == "undefined") {
throw exception
}
return errorMethod.call(observer, exception)
}
complete(value: unknown): void {
const subscription = this.#subscription
if (subscription.closed) {
return
}
const observer = getSubscriptionObserver(subscription)!
subscription.unsubscribe()
const completeMethod = getMethod(observer, "complete")
if (typeof completeMethod != "undefined") {
return completeMethod.call(observer, value)
}
}
}
declare global {
interface SymbolConstructor {
readonly observable: unique symbol
}
}