Slide 46
Slide 46 text
enum SchedulerState {
IDLE
=
"IDLE",
PENDING
=
"PENDING",
DONE
=
"DONE",
}
class Scheduler {
state: SchedulerState;
result: T;
worker: (data: T)
=
>
Generator;
iterator: Generator;
constructor(worker: (data: T)
=
>
Generator, initialResult: T) {
this.state
=
SchedulerState.IDLE;
this.worker
=
worker;
this.result
=
initialResult;
}
performUnitOfWork(data: T) {
switch (this.state) {
case "IDLE":
this.state
=
SchedulerState.PENDING;
this.iterator
=
this.worker(data);
throw Promise.resolve();
case "PENDING":
const { value, done }
=
this.iterator.next();
if (done) {
this.result
=
value;
this.state
=
SchedulerState.DONE;
return value;
}
throw Promise.resolve();
case "DONE":
this.state
=
SchedulerState.IDLE;
return this.result;
}
}
}