taskbuffer/ts/taskbuffer.classes.helpers.ts

97 lines
2.8 KiB
TypeScript
Raw Normal View History

2016-05-04 00:49:43 +00:00
/// <reference path="./typings/main.d.ts" />
import plugins = require("./taskbuffer.plugins");
import {Task} from "./taskbuffer.classes.task";
2016-05-04 00:49:43 +00:00
export let emptyTaskFunction = function(){
let done = plugins.Q.defer();
2016-05-04 00:49:43 +00:00
done.resolve();
return done.promise;
};
export let isTask = function(taskArg):boolean{
2016-05-04 00:49:43 +00:00
if(
taskArg instanceof Task
2016-05-04 00:49:43 +00:00
&& typeof taskArg.task === "function"
){
return true;
} else {
return false;
}
};
2016-05-06 00:05:45 +00:00
export let isTaskTouched = (taskArg:Task, touchedTasksArray:Task[]):boolean => {
let result = false;
for (let keyArg in touchedTasksArray){
if(taskArg === touchedTasksArray[keyArg]){
result = true;
}
}
return result;
}
2016-05-06 00:05:45 +00:00
export let runTask = function(taskArg:Task,optionsArg:{touchedTasksArray:Task[]} = {touchedTasksArray:[]}){
let done = plugins.Q.defer();
2016-05-06 00:05:45 +00:00
updateTaskStatus(taskArg,"running");
done.promise.then(function(){updateTaskStatus(taskArg,"idle")})
let localDeferred = plugins.Q.defer();
let touchedTasksArray:Task[];
if(optionsArg.touchedTasksArray){
touchedTasksArray = optionsArg.touchedTasksArray;
} else {
touchedTasksArray = [];
2016-05-04 00:49:43 +00:00
}
touchedTasksArray.push(taskArg);
localDeferred.promise
.then(() =>{
if(taskArg.preTask && !isTaskTouched(taskArg.preTask,touchedTasksArray)){
return runTask(taskArg.preTask,{touchedTasksArray:touchedTasksArray})
} else {
2016-05-06 00:05:45 +00:00
let done2 = plugins.Q.defer();
done2.resolve();
return done2.promise;
}
})
.then(() => {
return taskArg.task();
})
.then(() => {
if(taskArg.afterTask && !isTaskTouched(taskArg.afterTask,touchedTasksArray)){
return runTask(taskArg.afterTask,{touchedTasksArray:touchedTasksArray})
} else {
2016-05-06 00:05:45 +00:00
let done2 = plugins.Q.defer();
done2.resolve();
return done2.promise;
}
})
.then(() => {
done.resolve();
2016-05-06 00:05:45 +00:00
});
localDeferred.resolve();
2016-05-04 00:49:43 +00:00
return done.promise;
2016-05-05 17:21:01 +00:00
};
export let runBufferedTask = (taskArg:Task) => {
2016-05-06 00:05:45 +00:00
let recursiveBufferRunner = () => {
if(taskArg.bufferCounter > 0){
taskArg.bufferCounter--;
runTask(taskArg)
.then(recursiveBufferRunner);
}
}
}
export let updateTaskStatus = (taskArg,statusArg:string) => {
switch (statusArg) {
case "running":
taskArg.running = true;
taskArg.idle = false;
break;
case "idle":
taskArg.running = false;
taskArg.idle = true;
break;
default:
throw new Error("status not recognised");
}
}