feat: launch local-first Sudoku workbench
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
/// <reference lib="webworker" />
|
||||
|
||||
import { PuzzleValidationError } from "../domain";
|
||||
import {
|
||||
generateClassic,
|
||||
killerDigitCombinations,
|
||||
minimizePuzzle,
|
||||
solveExact,
|
||||
solveLogically,
|
||||
} from "../solver";
|
||||
import type {
|
||||
SolverWorkerRequest,
|
||||
SolverWorkerResponse,
|
||||
SolverWorkerValue,
|
||||
} from "./protocol";
|
||||
|
||||
const scope = self as unknown as DedicatedWorkerGlobalScope;
|
||||
|
||||
function run(request: SolverWorkerRequest): SolverWorkerValue {
|
||||
const operation = request.operation;
|
||||
switch (operation.kind) {
|
||||
case "solve":
|
||||
return solveExact(operation.puzzle, operation.options);
|
||||
case "logical":
|
||||
return solveLogically(operation.puzzle, operation.options);
|
||||
case "generate":
|
||||
return generateClassic(operation.options);
|
||||
case "minimize":
|
||||
return minimizePuzzle(operation.puzzle, operation.options);
|
||||
case "killer-combinations":
|
||||
return killerDigitCombinations(operation.options);
|
||||
}
|
||||
}
|
||||
|
||||
scope.addEventListener("message", (event: MessageEvent<unknown>) => {
|
||||
const input = event.data;
|
||||
if (
|
||||
typeof input !== "object" ||
|
||||
input === null ||
|
||||
typeof (input as { id?: unknown }).id !== "string" ||
|
||||
typeof (input as { operation?: unknown }).operation !== "object"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const request = input as SolverWorkerRequest;
|
||||
let response: SolverWorkerResponse;
|
||||
try {
|
||||
response = { id: request.id, ok: true, value: run(request) };
|
||||
} catch (error) {
|
||||
response = {
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: {
|
||||
name: error instanceof Error ? error.name : "Error",
|
||||
message:
|
||||
error instanceof Error ? error.message : "Unknown solver error",
|
||||
...(error instanceof PuzzleValidationError
|
||||
? { issues: error.issues }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
scope.postMessage(response);
|
||||
});
|
||||
|
||||
export {};
|
||||
Reference in New Issue
Block a user