From ede589dd6e171d766bfe500968335799daa049be Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Sat, 30 Nov 2024 12:50:53 +0100 Subject: [PATCH] Shorten the `WorkerMessageHandler` class a little bit - Use `this` in all scopes where that's possible, to avoid having to spell out `WorkerMessageHandler` everywhere. - Inline the `isMessagePort` helper function, since there's only a single call-site. - Use a static initialization block to move more code into the `WorkerMessageHandler` class itself. --- src/core/worker.js | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/src/core/worker.js b/src/core/worker.js index 533d8d01286ae..ecd0c52c0e7a5 100644 --- a/src/core/worker.js +++ b/src/core/worker.js @@ -70,9 +70,23 @@ class WorkerTask { } class WorkerMessageHandler { + static { + // Worker thread (and not Node.js)? + if ( + typeof window === "undefined" && + !isNodeJS && + typeof self !== "undefined" && + /* isMessagePort = */ + typeof self.postMessage === "function" && + "onmessage" in self + ) { + this.initializeFromPort(self); + } + } + static setup(handler, port) { let testMessageProcessed = false; - handler.on("test", function (data) { + handler.on("test", data => { if (testMessageProcessed) { return; // we already processed 'test' message once } @@ -82,13 +96,11 @@ class WorkerMessageHandler { handler.send("test", data instanceof Uint8Array); }); - handler.on("configure", function (data) { + handler.on("configure", data => { setVerbosityLevel(data.verbosity); }); - handler.on("GetDocRequest", function (data) { - return WorkerMessageHandler.createDocumentHandler(data, port); - }); + handler.on("GetDocRequest", data => this.createDocumentHandler(data, port)); } static createDocumentHandler(docParams, port) { @@ -879,25 +891,9 @@ class WorkerMessageHandler { static initializeFromPort(port) { const handler = new MessageHandler("worker", "main", port); - WorkerMessageHandler.setup(handler, port); + this.setup(handler, port); handler.send("ready", null); } } -function isMessagePort(maybePort) { - return ( - typeof maybePort.postMessage === "function" && "onmessage" in maybePort - ); -} - -// Worker thread (and not Node.js)? -if ( - typeof window === "undefined" && - !isNodeJS && - typeof self !== "undefined" && - isMessagePort(self) -) { - WorkerMessageHandler.initializeFromPort(self); -} - export { WorkerMessageHandler, WorkerTask };