ソースを参照

[chunkedForEach]: add method to execute an array loop in chunks

mightyplow 7 年 前
コミット
3f3cf77d3f
3 ファイル変更37 行追加5 行削除
  1. 30 0
      src/array/chunkedForEach.js
  2. 2 1
      src/array/index.js
  3. 5 4
      src/index.js

+ 30 - 0
src/array/chunkedForEach.js

@@ -0,0 +1,30 @@
+import checkArray from './_checkArray';
+
+const $postMessage = typeof postMessage !== 'undefined' && postMessage;
+
+const mkExecNextMessage = (values, fn, resolve, chunkSize, msg) => function execNext ({ data }) {
+    if (data !== msg) { return; }
+
+    if (values.length) {
+        values.splice(0, chunkSize).forEach(fn);
+        $postMessage(msg, '*');
+    } else {
+        resolve();
+        window.removeEventListener('message', execNext);
+    }
+};
+
+const createSplitMessage = () => `FOR_EACH_SPLIT_${Math.floor(Math.random() * 10000)}`;
+
+const chunkedForEach = (ar = [], fn = Function.prototype, chunkSize = 1) => {
+    checkArray(ar);
+    if (!$postMessage) { throw Error('postMessage not available'); }
+
+    return new Promise((resolve, reject) => {
+        const streamMessage = createSplitMessage();
+        window.addEventListener('message', mkExecNextMessage([...ar], fn, resolve, chunkSize, streamMessage));
+        $postMessage(streamMessage, '*');
+    });
+};
+
+export default chunkedForEach;

+ 2 - 1
src/array/index.js

@@ -3,7 +3,8 @@
  */
 export { default as ensureArray} from './ensureArray';
 export { default as flatten } from './flatten';
+export { default as chunkedForEach } from './chunkedForEach';
 export { default as head } from './head';
 export { default as tail } from './tail';
-export { default as to } from './toArray';
+export { default as toArray } from './toArray';
 export { default as unique } from './unique';

+ 5 - 4
src/index.js

@@ -1,10 +1,11 @@
 export {
     ensureArray,
-    unique,
-    tail,
-    head,
     flatten,
-    to
+    chunkedForEach,
+    head,
+    tail,
+    toArray,
+    unique
 } from './array';
 
 export {