diff --git a/src/ch08/exercises.ts b/src/ch08/exercises.ts index d22cb87..ee5e16b 100644 --- a/src/ch08/exercises.ts +++ b/src/ch08/exercises.ts @@ -57,7 +57,7 @@ function createProtocol
(script: string) { new Promise
((resolve, reject) => {
let worker = new Worker(script)
worker.onerror = reject
- worker.onmessage = event => resolve(event.data.data)
+ worker.onmessage = event => resolve(event.data)
worker.postMessage({command, args})
})
}
@@ -73,32 +73,59 @@ parallelDeterminant([[1, 2], [3, 4]]).then(
// WorkerScript.ts
-let handlers: {
- [C in keyof MatrixProtocol]: (
- ...args: MatrixProtocol[C]['in']
- ) => MatrixProtocol[C]['out']
-} = {
- determinant(matrix) {
- return determinant(matrix)
- },
- ['dot-product'](a, b) {
- return dotProduct(a, b)
- },
- invert(matrix) {
- return invert(matrix)
+type Data<
+ P extends Protocol,
+ C extends keyof P = keyof P
+> = C extends C
+ ? {command: C; args: P[C]['in']}
+ : never
+
+function handle(
+ data: Data (script: string) {
+ return ((resolve, reject) => {
+ let child = fork(script)
+ child.on('error', reject)
+ child.on('message', resolve)
+ child.send({command, args})
+ })
+}
+
+let runWithMatrixProtocolCP = createProtocolCP