2018-12-09 01:17:33 +08:00
|
|
|
import {Utils} from '../../../common/Utils';
|
2017-07-24 04:37:29 +08:00
|
|
|
|
|
|
|
|
2018-12-09 01:17:33 +08:00
|
|
|
export interface TaskQueEntry<I, O> {
|
|
|
|
data: I;
|
|
|
|
promise: { obj: Promise<O>, resolve: Function, reject: Function };
|
2017-07-24 04:37:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2018-12-09 01:17:33 +08:00
|
|
|
export class TaskQue<I, O> {
|
2017-07-24 04:37:29 +08:00
|
|
|
|
2018-12-09 01:17:33 +08:00
|
|
|
private tasks: TaskQueEntry<I, O>[] = [];
|
|
|
|
private processing: TaskQueEntry<I, O>[] = [];
|
2017-07-24 04:37:29 +08:00
|
|
|
|
2018-12-09 01:17:33 +08:00
|
|
|
constructor() {
|
2017-07-24 04:37:29 +08:00
|
|
|
}
|
|
|
|
|
2018-12-09 01:17:33 +08:00
|
|
|
|
|
|
|
private getSameTask(input: I): TaskQueEntry<I, O> {
|
|
|
|
return this.tasks.find(t => Utils.equalsFilter(t.data, input)) ||
|
|
|
|
this.processing.find(t => Utils.equalsFilter(t.data, input));
|
|
|
|
}
|
|
|
|
|
|
|
|
private putNewTask(input: I): TaskQueEntry<I, O> {
|
|
|
|
const taskEntry: TaskQueEntry<I, O> = {
|
|
|
|
data: input,
|
|
|
|
promise: {
|
|
|
|
obj: null,
|
|
|
|
resolve: null,
|
|
|
|
reject: null
|
|
|
|
}
|
|
|
|
};
|
|
|
|
this.tasks.push(taskEntry);
|
|
|
|
taskEntry.promise.obj = new Promise<O>((resolve: Function, reject: Function) => {
|
|
|
|
taskEntry.promise.reject = reject;
|
|
|
|
taskEntry.promise.resolve = resolve;
|
2017-07-24 04:37:29 +08:00
|
|
|
});
|
2018-12-09 01:17:33 +08:00
|
|
|
return taskEntry;
|
|
|
|
}
|
|
|
|
|
|
|
|
public isEmpty(): boolean {
|
|
|
|
return this.tasks.length === 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
public add(input: I): TaskQueEntry<I, O> {
|
|
|
|
return (this.getSameTask(input) || this.putNewTask(input));
|
|
|
|
}
|
|
|
|
|
|
|
|
public get(): TaskQueEntry<I, O> {
|
|
|
|
const task = this.tasks.shift();
|
|
|
|
this.processing.push(task);
|
|
|
|
return task;
|
|
|
|
}
|
|
|
|
|
|
|
|
public ready(task: TaskQueEntry<I, O>): void {
|
|
|
|
this.processing.slice(this.processing.indexOf(task), 1);
|
2017-07-24 04:37:29 +08:00
|
|
|
}
|
|
|
|
}
|