From 9a20e41ec6253e8f217cebc42d49aacb7707a772 Mon Sep 17 00:00:00 2001 From: KoroLion Date: Thu, 29 Apr 2021 22:31:44 +0300 Subject: [PATCH] parallel.js --- array.size.js => src/array.size.js | 0 src/parallel.js | 52 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) rename array.size.js => src/array.size.js (100%) create mode 100644 src/parallel.js diff --git a/array.size.js b/src/array.size.js similarity index 100% rename from array.size.js rename to src/array.size.js diff --git a/src/parallel.js b/src/parallel.js new file mode 100644 index 0000000..624bc89 --- /dev/null +++ b/src/parallel.js @@ -0,0 +1,52 @@ +// Параллельные вычисления + +const WAIT_CHECK_TIME = 10; + +function parallel(promises, callback) { + const result = []; + + let done = 0; + const setResult = (i, res) => { + done++; + result[i] = res; + } + for (let i in promises) { + const promise = promises[i]; + const res = promise((res) => setResult(i, res)); + if (res) { + setResult(i, res); + } + } + + // if all sync + if (done === promises.length) { + callback(result); + return; + } + + // if at least one is async + const waitInterval = setInterval(() => { + if (done === promises.length) { + clearInterval(waitInterval); + callback(result); + } + }, WAIT_CHECK_TIME); +} + +parallel([ + function (resolve) { + setTimeout(function () { + resolve(10); + }, 50); + }, + function () { + return 5; + }, + function (resolve) { + setTimeout(function () { + resolve(0); + }, 10) + } +], function (results) { + console.log(results); // [10, 5, 0] +});