1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2024-11-03 21:04:03 +08:00
pigallery2/backend/model/threading/TaskQue.ts

63 lines
1.5 KiB
TypeScript
Raw Normal View History

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 {
2018-12-22 07:09:07 +08:00
const index = this.processing.indexOf(task);
if (index === -1) {
throw new Error('Task does not exist');
}
this.processing.splice(index, 1);
2017-07-24 04:37:29 +08:00
}
}