@ixily/activ
Version:
Alpha Capture Trade Idea Verification. Blockchain ownership proven trade ideas and strategies.
85 lines (74 loc) • 2.1 kB
text/typescript
import { rest } from '../..'
type Task = () => Promise<void>
interface PoolStack {
id: string
sequentialPoolStack: Task[]
sequentialPoolRunningStack: Task[]
solvingSequentialPool: boolean
}
const state = {
sequentialPools: new Map<string, PoolStack>(),
}
const processSequentialPool = async (id: string) => {
if (state.sequentialPools.get(id)!.sequentialPoolStack.length > 0) {
// take all elements from pool
state.sequentialPools.get(id)!.sequentialPoolRunningStack =
state.sequentialPools
.get(id)!
.sequentialPoolStack.splice(
0,
state.sequentialPools.get(id)!.sequentialPoolStack.length,
)
for (const task of state.sequentialPools.get(id)!
.sequentialPoolRunningStack) {
await task()
}
state.sequentialPools.get(id)!.sequentialPoolRunningStack = []
}
if (state.sequentialPools.get(id)!.sequentialPoolStack.length !== 0) {
setTimeout(() => {
solveSequentialPool(id)
}, 10)
}
}
const solveSequentialPool = async (id: string) => {
if (!state.sequentialPools.get(id)!.solvingSequentialPool) {
state.sequentialPools.get(id)!.solvingSequentialPool = true
await rest(10)
await processSequentialPool(id)
state.sequentialPools.get(id)!.solvingSequentialPool = false
}
}
const addAndSolveSequentialPool = (id: string, task: () => Promise<void>) => {
if (!state.sequentialPools.has(id)) {
state.sequentialPools.set(id, {
id,
sequentialPoolStack: [] as Task[],
sequentialPoolRunningStack: [] as Task[],
solvingSequentialPool: false,
})
}
state.sequentialPools.get(id)!.sequentialPoolStack.push(task)
solveSequentialPool(id)
}
const runSequentialTicket = async <T>(
params: string[],
task: () => Promise<T>,
): Promise<T> => {
const id = params.join('|')
const promisedResult = new Promise<T>(async (resolve, reject) => {
const executeTask = async () => {
try {
const result = await task()
resolve(result)
} catch (err) {
reject(err)
}
}
addAndSolveSequentialPool(id, executeTask)
})
return promisedResult
}
export const IdeaTrafficDirectorModule = {
runSequentialTicket,
}