Compare commits
4 Commits
3c6d69c343
...
5ccbb2ef1c
Author | SHA1 | Date | |
---|---|---|---|
5ccbb2ef1c | |||
da1405f262 | |||
2f8801bae6 | |||
67ec0d5430 |
@ -34,15 +34,7 @@ function initialize() {
|
||||
}
|
||||
initialize();
|
||||
|
||||
/**
|
||||
* Awaits a promise with a timeout.
|
||||
*
|
||||
* @param promise the promise to await
|
||||
* @param ms the timeout in milliseconds
|
||||
* @param cb a callback to call when the timeout is reached. The promise is
|
||||
* rejected with whatever gets returned here.
|
||||
*/
|
||||
function withTimeout<T>(promise: Promise<T>, ms: number, cb: () => any) {
|
||||
function withTimeout<T>(promise: Promise<T>, ms: number, cb: () => Error) {
|
||||
let timeout: NodeJS.Timeout;
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
@ -57,27 +49,31 @@ export async function generate(
|
||||
regionHeight: number,
|
||||
clues: number
|
||||
): Promise<Sudoku> {
|
||||
const proxy = available.pop();
|
||||
const proxy = available.shift();
|
||||
if (!proxy) {
|
||||
throw new Error("No workers available right now. Please try again.");
|
||||
}
|
||||
|
||||
const puzzle = await withTimeout<number[]>(
|
||||
proxy.generate(regionWidth, regionHeight, clues),
|
||||
TIMEOUT,
|
||||
() => {
|
||||
Thread.terminate(proxy);
|
||||
getWorker().then((worker) => available.push(worker));
|
||||
return new Error("Timed out. Try reducing the number of clues.");
|
||||
}
|
||||
);
|
||||
try {
|
||||
const puzzle: number[] = await withTimeout(
|
||||
proxy.generate(regionWidth, regionHeight, clues),
|
||||
TIMEOUT,
|
||||
() => {
|
||||
Thread.terminate(proxy);
|
||||
getWorker().then((worker) => available.push(worker));
|
||||
return new Error("Timed out. Try reducing the number of clues.");
|
||||
}
|
||||
);
|
||||
|
||||
available.push(proxy);
|
||||
prettyPrint(regionWidth, regionHeight, puzzle);
|
||||
return {
|
||||
regionWidth,
|
||||
regionHeight,
|
||||
size: (regionWidth * regionHeight) ** 2,
|
||||
cells: puzzle,
|
||||
};
|
||||
available.unshift(proxy);
|
||||
prettyPrint(regionWidth, regionHeight, puzzle);
|
||||
return {
|
||||
regionWidth,
|
||||
regionHeight,
|
||||
size: (regionWidth * regionHeight) ** 2,
|
||||
cells: puzzle,
|
||||
};
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user