From f7924820649d1a2f488bc72746b13df025be8c0f Mon Sep 17 00:00:00 2001 From: Walle Cyril Date: Mon, 15 Jul 2019 22:10:32 +0200 Subject: [PATCH] use named parameters --- example-deno/file_usage.js | 2 +- example-node/file_usage.js | 2 +- example/example.js | 48 +++++++++++----------- example/worka.html | 6 +-- example/workaRunTimeError.html | 8 ++-- example/workaSyntaxError.html | 4 +- readme.md | 75 ++++++++++++++++++++-------------- source/worka.js | 59 +++++++++++++------------- 8 files changed, 106 insertions(+), 98 deletions(-) diff --git a/example-deno/file_usage.js b/example-deno/file_usage.js index 94cda24..fcc871a 100644 --- a/example-deno/file_usage.js +++ b/example-deno/file_usage.js @@ -16,7 +16,7 @@ registerWorker({ loadMode: FILE }); -work(`sort`, [1, 2, 3, -8, -5, 2, 3, 45, 5]).then(function (result) { +work({ name: `sort`, input: [1, 2, 3, -8, -5, 2, 3, 45, 5] }).then(function (result) { console.log(result); console.log(`after success`); }).catch(error => { diff --git a/example-node/file_usage.js b/example-node/file_usage.js index 140bca2..bc2956f 100644 --- a/example-node/file_usage.js +++ b/example-node/file_usage.js @@ -11,7 +11,7 @@ registerWorker({ loadMode: FILE }); -work(`sort`, [1, 2, 3, -8, -5, 2, 3, 45, 5]).then(function (result) { +work({ name: `sort`, input: [1, 2, 3, -8, -5, 2, 3, 45, 5] }).then(function (result) { console.log(result); console.log(`after success`); }).catch(error => { diff --git a/example/example.js b/example/example.js index 0638af5..3af7891 100644 --- a/example/example.js +++ b/example/example.js @@ -17,9 +17,9 @@ import { import estimatePi from "./estimatePi.js"; import { estimatePiWorkerURL } from "./estimatePiPrepared.js"; -const ESTIMATEPI_RAW_WORKER_URL = "estimatePiWorker.js"; -const ESTIMATEPI_RAW_WORKER_URL_NO_CACHE = "estimatePiWorkerNoCache.js"; -const ESTIMATE_PI_ACTION = "estimatePi"; +const ESTIMATEPI_RAW_WORKER_URL = `estimatePiWorker.js`; +const ESTIMATEPI_RAW_WORKER_URL_NO_CACHE = `estimatePiWorkerNoCache.js`; +const ESTIMATE_PI_ACTION = `estimatePi`; const SAMPLE_SIZE = 10; const INITIAL_PRECISION_LEVEL = 2 || 5; @@ -39,13 +39,13 @@ let precision = precisionFromPrecisionLevel(INITIAL_PRECISION_LEVEL); registerWorker({ - name: "getPiEstimation", + name: `getPiEstimation`, resource: estimatePi, loadMode: FUNCTION }); registerWorker({ - name: "getPiEstimationForceRestart", + name: `getPiEstimationForceRestart`, resource: estimatePi, loadMode: FUNCTION, hope: 5 @@ -54,16 +54,16 @@ registerWorker({ d.functions.setPrecision = function () { - precision = precisionFromPrecisionLevel(Number(d.variables["precisionLevel"])); + precision = precisionFromPrecisionLevel(Number(d.variables[`precisionLevel`])); }; d.functions.webWorkerPreloaded = function () { const startTime = getReferenceTime(); const worker = new Worker(estimatePiWorkerURL); - worker.addEventListener("message", function (event) { + worker.addEventListener(`message`, function (event) { const message = event.data; - if (message.hasOwnProperty("result")) { + if (message.hasOwnProperty(`result`)) { const result = message.result; const endTime = getReferenceTime(); const duration = endTime - startTime; @@ -86,9 +86,9 @@ d.functions.webWorkerNoCache = function () { const startTime = getReferenceTime(); const worker = new Worker(ESTIMATEPI_RAW_WORKER_URL_NO_CACHE); - worker.addEventListener("message", function (event) { + worker.addEventListener(`message`, function (event) { const message = event.data; - if (message.hasOwnProperty("result")) { + if (message.hasOwnProperty(`result`)) { const result = message.result; const endTime = getReferenceTime(); @@ -112,9 +112,9 @@ d.functions.webWorkerWithCache = function () { const startTime = getReferenceTime(); const worker = new Worker(ESTIMATEPI_RAW_WORKER_URL); - worker.addEventListener("message", function (event) { + worker.addEventListener(`message`, function (event) { const message = event.data; - if (message.hasOwnProperty("result")) { + if (message.hasOwnProperty(`result`)) { const result = message.result; const endTime = getReferenceTime(); @@ -188,7 +188,7 @@ const addAggregatesStats = function (aggregates) { const testWithoutWorker = function () { const aggregates = { - title: "Without Web Worker", + title: `Without Web Worker`, totalComputationTime: 0, meanTime: 0, totalTime: 0, @@ -219,7 +219,7 @@ const testWithoutWorker = function () { const testWithRemoteServer = function () { const aggregates = { - title: "With Remote Server", + title: `With Remote Server`, totalComputationTime: 0, meanTime: 0, totalTime: 0, @@ -258,7 +258,7 @@ const testWithRemoteServer = function () { const testWithRawWorker = function () { const aggregates = { - title: "With Raw Web Worker", + title: `With Raw Web Worker`, totalComputationTime: 0, meanTime: 0, totalTime: 0, @@ -271,9 +271,9 @@ const testWithRawWorker = function () { return new Promise(function (resolve, reject) { const startTime = getReferenceTime(); const worker = new Worker(ESTIMATEPI_RAW_WORKER_URL); - worker.addEventListener("message", function (event) { + worker.addEventListener(`message`, function (event) { const message = event.data; - if (message.hasOwnProperty("result")) { + if (message.hasOwnProperty(`result`)) { const piEstimation = message.result; const endTime = getReferenceTime(); const duration = endTime - startTime; @@ -307,7 +307,7 @@ const testWithRawWorker = function () { const testWithWorkerCreatedEveryTime = function () { const aggregates = { - title: "With Web Worker Created every time (worka)", + title: `With Web Worker Created every time (worka)`, totalComputationTime: 0, meanTime: 0, totalTime: 0, @@ -318,7 +318,7 @@ const testWithWorkerCreatedEveryTime = function () { const workerWork = function () { return timePromise(function () { - return work("getPiEstimationForceRestart", precision).catch(console.error); + return work({ name: `getPiEstimationForceRestart`, input: precision }).catch(console.error); }).then(function ({ timeElapsed, value }) { aggregates.totalComputationTime += timeElapsed; return { @@ -341,7 +341,7 @@ const testWithWorkerCreatedEveryTime = function () { const testWithWorker = function () { const aggregates = { - title: "With Web Worker (worka)", + title: `With Web Worker (worka)`, totalComputationTime: 0, meanTime: 0, totalTime: 0, @@ -352,13 +352,13 @@ const testWithWorker = function () { const workerWork = function () { return timePromise(function () { - return work("getPiEstimation", precision).catch(console.error); + return work({ name: `getPiEstimation`, input: precision }).catch(console.error); }).then(function ({ timeElapsed, value }) { aggregates.totalComputationTime += timeElapsed; return { precision, duration: timeElapsed, - piEstimation: value + piEstimation: value, }; }); }; @@ -375,7 +375,7 @@ const testWithWorker = function () { const testWithWorkerAutoSplit = function () { const aggregates = { - title: "With Web Worker auto split (worka)", + title: `With Web Worker auto split (worka)`, totalComputationTime: 0, meanTime: 0, totalTime: 0, @@ -386,7 +386,7 @@ const testWithWorkerAutoSplit = function () { const workerWork = function () { return timePromise(function () { - return work("getPiEstimation", precision).catch(console.error); + return work({ name: `getPiEstimation`, input: precision }).catch(console.error); }).then(function ({ timeElapsed, value }) { aggregates.totalComputationTime += timeElapsed; return { diff --git a/example/worka.html b/example/worka.html index 734e87a..8801480 100644 --- a/example/worka.html +++ b/example/worka.html @@ -16,14 +16,14 @@ }; registerWorker({ - name: "sort", + name: `sort`, resource: sort, loadMode: FUNCTION }); -work("sort", [1, 2, 3, -8, -5, 2, 3, 45, 5]).then(function (result) { +work({name: `sort`, input: [1, 2, 3, -8, -5, 2, 3, 45, 5]}).then(function (result) { console.log(result); - console.log("after success"); + console.log(`after success`); }); diff --git a/example/workaRunTimeError.html b/example/workaRunTimeError.html index 9357da2..cea382f 100644 --- a/example/workaRunTimeError.html +++ b/example/workaRunTimeError.html @@ -16,16 +16,16 @@ }; registerWorker({ - name: "sort", + name: `sort`, resource: sort, loadMode: FUNCTION }); -work("sort", [1, 2, 3, -8, -5, 2, 3, 45, 5]).then(function (result) { +work({name: `sort`, input: [1, 2, 3, -8, -5, 2, 3, 45, 5]}).then(function (result) { console.log(result); - console.log("after success"); + console.log(`after success`); }).catch(function (error) { - console.log("in the catch"); + console.log(`in the catch`); console.error(error); }); diff --git a/example/workaSyntaxError.html b/example/workaSyntaxError.html index 83fece9..b2a072a 100644 --- a/example/workaSyntaxError.html +++ b/example/workaSyntaxError.html @@ -17,15 +17,13 @@ return array; }`; -console.log("1"); registerWorker({ name: "sort", resource: sort, loadMode: STRING }); -console.log("2"); -work("sort", [1, 2, 3, -8, -5, 2, 3, 45, 5]).then(function (result) { +work({name: `sort`, input: [1, 2, 3, -8, -5, 2, 3, 45, 5]}).then(function (result) { console.log(result); console.log("after success"); }).catch(function (error) { diff --git a/readme.md b/readme.md index a9e5b39..530ccd6 100644 --- a/readme.md +++ b/readme.md @@ -57,12 +57,12 @@ const sort = function (array) { }; registerWorker({ - name: "sort", + name: `sort`, resource: sort, loadMode: FUNCTION, }); -work("sort", [1, 2, 3, -8, -5, 2, 3, 45, 5]).then(function (result) { +work({name: `sort`, input: [1, 2, 3, -8, -5, 2, 3, 45, 5]}).then(function (result) { // result is a copy console.log(result); }); @@ -128,7 +128,7 @@ Describes the worker. Example: ``` { - name: "workerName", + name: `workerName`, resource: myFunction, loadMode: FUNCTION, lazy: 5, @@ -193,15 +193,24 @@ const returnsMultipleFunctions = function () { }; registerWorker({ - name: "test", + name: `test`, resource: returnsMultipleFunctions, loadMode: MULTI_FUNCTION }); -work("test/sort", [1,2,3,-8,-5,2,3,45,5]).then(function (result) { +work({ + name: `test`, + functionName: `sort`, + input: [1,2,3,-8,-5,2,3,45,5], +}).then(function (result) { console.log(result); }); -work("test/addNegativeLength", [1,2,3,-845,5]).then(function (result) { + +work({ + name: `test`, + functionName: `addNegativeLength`, + input: [1,2,3,-845,5], +}).then(function (result) { console.log(result); }); ``` @@ -241,15 +250,15 @@ const statefullGenerator = function () { }; registerWorker({ - name: "stateTest", + name: `stateTest`, resource: statefullGenerator, loadMode: FUNCTION, stateless: false }); -work("stateTest", 5).then(function (result) { +work({name: `stateTest`, input: 5}).then(function (result) { console.log(result); // 5 - return work("stateTest", 5); + return work(name: `stateTest`, input: 5}); }).then(function (result) { console.log(result); // 10 }); @@ -275,14 +284,14 @@ Partial Default const functionReturner = function () { const largeConstantInitialization = [ - "could be a long array", - "or something that would be", - "costly to create each time" + `could be a long array`, + `or something that would be`, + `costly to create each time` ]; let recursiveFunction; - recursiveFunction = function ({input = "", tree}) { + recursiveFunction = function ({input = ``, tree}) { const localTextContent = tree.textContent; const allTextContent = `${input} > ${localTextContent}`; if (tree.child) { @@ -294,28 +303,28 @@ const functionReturner = function () { }; registerWorker({ - name: "initializationTest", + name: `initializationTest`, resource: functionReturner, loadMode: FUNCTION, initialize: true }); const recursiveDataStruct = { - textContent: "top level", + textContent: `top level`, child: { - textContent: "middle level", + textContent: `middle level`, child: { - textContent: "bottom level", + textContent: `bottom level`, child: { - textContent: "underground", + textContent: `underground`, child: { - textContent: "-10" + textContent: `-10` } } } } }; -work("initializationTest", {tree: recursiveDataStruct}) +work({name: `initializationTest`, input: {tree: recursiveDataStruct}}) .then(function (result) { console.log(result); // > top level > middle level > bottom level > underground > -10 @@ -412,23 +421,23 @@ Partial Default ### work -`work(name, input);` +`work({name, input, functionName});` Returns a promise that eventually resolves with the result or fails. Use registerWorker first ! ```js -work("test/sort", [1,2,3,-8,-5,2,3,45,5]).then(function (result) { +work({name:`test/sort`, input: [1,2,3,-8,-5,2,3,45,5]}).then(function (result) { console.log(result); }).catch(function (reason) { if (reason === NO_SUPPORT_ERROR) { - console.error("Web Worker API not supported"); + console.error(`Web Worker API not supported`); } else if (reason === TIME_OUT_ERROR) { // can only happen with a worker registered with a timeOut - console.error("Took longer than expected"); + console.error(`Took longer than expected`); } else { - console.error("other error", reason); + console.error(`other error`, reason); } }); ``` @@ -477,7 +486,7 @@ const fetchFromNetwork = function (precision) { }); }; -const promise = work("getPiEstimation", precision).catch(function (error) { +const promise = work({name: `getPiEstimation`,input: precision}).catch(function (error) { if (error === NO_SUPPORT_ERROR) { return fetchFromNetwork(precision); } else { @@ -499,7 +508,7 @@ const promise = fetch(`../estimatePi?input=${precision}`, {}).then(function (res const result = Number(resultString); return result; }).catch(function (noNetwork) { - return work("getPiEstimation", precision); + return work({name: `getPiEstimation`, input: precision}); }); ``` @@ -518,7 +527,7 @@ const fetchFromNetwork = function (precision) { }; const promise = Promise.race([ - work("getPiEstimation", precision), + work({name: `getPiEstimation`, input: precision}), fetchFromNetwork(precision) ]); @@ -542,14 +551,14 @@ import promiseMemoize from "promise-memoize"; // register worker registerWorker({ - name: "getPiEstimation", + name: `getPiEstimation`, resource: estimatePi, loadMode: FUNCTION }); // create memoized version const memoized = promiseMemoize(function(precision) { - return work("getPiEstimationForceRestart", precision); + return work({name: `getPiEstimationForceRestart`, input: precision}); }); // use it @@ -637,7 +646,7 @@ Feel free to open issue to know more. ### The name -"worka" was chosen to keep it short and "worker" was already taken. +*worka* was chosen to keep it short and *worker* was already taken. ### Updates @@ -646,6 +655,10 @@ Feel free to open issue to know more. Symbols are exported individually +work expects an object as argument + +for MULTI_FUNCTION, functionName is separated from name + #### 7.0.0 Move to ES Module first diff --git a/source/worka.js b/source/worka.js index f0ca870..8a5cd56 100644 --- a/source/worka.js +++ b/source/worka.js @@ -44,8 +44,10 @@ const DECORATED_FILE = Symbol(); // errors const NO_SUPPORT_ERROR = Symbol(); const TIME_OUT_ERROR = Symbol(); -const SPLIT = `/`; + +// private const JS_MIME = { type: `text/javascript` }; +const USE_STRICT = `"use strict";`; let max = 1; if (typeof navigator === `object`) { @@ -91,7 +93,6 @@ const loadWorker = function (worker) { worker.loaded = true; }; -const useStrict = `"use strict";`; /* convert to String because errorEvent can not be cloned*/ const errorHandler = `self.addEventListener(\`error\`, function (errorEvent) { errorEvent.preventDefault(); @@ -111,7 +112,7 @@ const decorateWorker = function (worker) { let decoratedAsString; if (loadMode === MULTI_FUNCTION) { decoratedAsString = ` -${useStrict} +${USE_STRICT} ${errorHandler} const functions = ${originalAsString}(); self.addEventListener(\`message\`, function(event) { @@ -141,7 +142,7 @@ self.addEventListener(\`message\`, function(event) { initializeSuffix = `()`; } decoratedAsString = ` -${useStrict} +${USE_STRICT} ${errorHandler} const doWork = ${originalAsString}${initializeSuffix}; self.addEventListener(\`message\`, function(event) { @@ -367,29 +368,13 @@ const workerWithLowestResolveQueue = function (workers) { }); }; -const work = function (name, input, workerStore = workers, forceWork = false) { - /* is overloaded on many levels, could benefit from refactoring - functionName not needed ? */ +const work = function ({ name, functionName, input, workerStore = workers, forceWork = false }) { if (!workerSupport.basic) { return Promise.reject(NO_SUPPORT_ERROR); } let preparedInput; - let workerName; - let functionName; - if (Array.isArray(name)) { - [workerName, functionName] = name; - } else { - const nameSplit = name.split(SPLIT); - if (nameSplit.length === 2) { - // worker.loadMode === MULTI_FUNCTION - [workerName, functionName] = nameSplit; - - } else { - workerName = name; - } - } - if (!Object.prototype.hasOwnProperty.call(workerStore, workerName)) { - return Promise.reject(`${workerName} not registered`); + if (!Object.prototype.hasOwnProperty.call(workerStore, name)) { + return Promise.reject(`${name} not registered`); } if (Object.prototype.hasOwnProperty.call(input, `input`)) { // already prepared @@ -402,7 +387,7 @@ const work = function (name, input, workerStore = workers, forceWork = false) { preparedInput.functionName = functionName; } } - const worker = workerStore[workerName]; + const worker = workerStore[name]; if (worker.stateless && worker.resolveRejectQueue.length !== 0 && !forceWork) { /* the worker is already doing something and it is stateless @@ -428,11 +413,12 @@ const work = function (name, input, workerStore = workers, forceWork = false) { const workerWithEmptyQueue = findWorkerWithEmptyQueue(worker.coWorkers); if (workerWithEmptyQueue) { // at least 1 is idle, give it something to do - return work( - [workerWithEmptyQueue.name, functionName], - preparedInput, - worker.coWorkers - ); + return work({ + name: workerWithEmptyQueue.name, + functionName, + input: preparedInput, + workerStore: worker.coWorkers, + }); } } @@ -443,7 +429,12 @@ const work = function (name, input, workerStore = workers, forceWork = false) { const nameNow = worker.nextCoWorkerOptions.name; registerWorker(worker.nextCoWorkerOptions, worker.coWorkers); worker.nextCoWorkerOptions.name = String(Number(nameNow) + 1); - return work([nameNow, functionName], preparedInput, worker.coWorkers); + return work({ + name: nameNow, + functionName, + input: preparedInput, + workerStore: worker.coWorkers, + }); } /* search for the worker with the lowest resolution queue and delegate to it @@ -451,7 +442,13 @@ const work = function (name, input, workerStore = workers, forceWork = false) { const bestWorker = workerWithLowestResolveQueue( Object.values(worker.coWorkers).concat(worker) ); - return work([bestWorker.name, functionName], preparedInput, bestWorker.workerStore, true); + return work({ + name: bestWorker.name, + functionName, + input: preparedInput, + workerStore: bestWorker.workerStore, + forceWork: true + }); } // normal case