-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6c00b3c
commit 2d0ab0d
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
export class Deferred<T> { | ||
promise: Promise<T> = new Promise<T>(() => {}) | ||
resolve: (value: T | PromiseLike<T>) => void = () => {} | ||
reject: (reason?: any) => void = () => {} | ||
|
||
constructor() { | ||
Check failure on line 6 in discojs/discojs-web/src/dataset/data_loader/cache.ts GitHub Actions / lint-lib-web
|
||
this.reset() | ||
} | ||
|
||
reset() { | ||
Check failure on line 10 in discojs/discojs-web/src/dataset/data_loader/cache.ts GitHub Actions / lint-lib-web
Check failure on line 10 in discojs/discojs-web/src/dataset/data_loader/cache.ts GitHub Actions / lint-lib-web
|
||
this.promise = new Promise<T>((resolve, reject) => { | ||
this.resolve = resolve | ||
this.reject = reject | ||
}) | ||
} | ||
} | ||
|
||
export class Cache<E> { | ||
position: number = 0 | ||
private readonly cache: Deferred<E>[] | ||
|
||
private constructor( | ||
readonly length: number, | ||
private readonly request: ( | ||
pos: number, | ||
init?: boolean | ||
) => void | Promise<void> | ||
) { | ||
this.cache = Array.from({ length }, () => new Deferred<E>()) | ||
} | ||
|
||
// pre-loads the cache with the first n requests | ||
static async init<E>( | ||
length: number, | ||
request: (pos: number, init?: boolean) => void | Promise<void>, | ||
initializer: (c: Cache<E>) => void | ||
): Promise<Cache<E>> { | ||
const cache = new Cache<E>(length, request) | ||
initializer(cache) | ||
for (let pos = 0; pos < length; pos++) { | ||
cache.request(pos, true) | ||
} | ||
return cache | ||
} | ||
|
||
put(pos: number, elt: E): void { | ||
const promise = this.cache[pos] as Deferred<E> | ||
promise.resolve(elt) | ||
} | ||
|
||
async next(): Promise<E> { | ||
const eltOrDeffered = this.cache[this.position] | ||
const elt = await eltOrDeffered.promise | ||
const pos = this.position | ||
this.cache[pos] = new Deferred<E>() | ||
this.request(pos) | ||
this.position = (pos + 1) % this.length | ||
return elt | ||
} | ||
} |