|
144 | 144 | return this; |
145 | 145 | }; |
146 | 146 |
|
| 147 | + Parallel.prototype._spawnReduceWorker = function (data, cb, done) { |
| 148 | + var that = this; |
| 149 | + var wrk = new Worker(that.options.path); |
| 150 | + wrk.postMessage(Parallel.getWorkerSource(cb)); |
| 151 | + wrk.postMessage(data); |
| 152 | + wrk.onmessage = function (msg) { |
| 153 | + wrk.terminate(); |
| 154 | + that.data[that.data.length] = msg.data; |
| 155 | + done(); |
| 156 | + }; |
| 157 | + }; |
| 158 | + |
| 159 | + Parallel.prototype.reduce = function (cb) { |
| 160 | + if (!this.data.length) { |
| 161 | + throw new Error('Can\'t reduce non-array data'); |
| 162 | + } |
| 163 | + |
| 164 | + var that = this; |
| 165 | + function done(data) { |
| 166 | + if (that.data.length === 1) { |
| 167 | + that.data = that.data[0]; |
| 168 | + newOp.resolve(null, that.data); |
| 169 | + } else { |
| 170 | + that._spawnReduceWorker([that.data[0], that.data[1]], cb, done); |
| 171 | + that.data.splice(0, 2); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + var newOp = new Operation(); |
| 176 | + this.operation.then(function () { |
| 177 | + if (that.data.length === 1) { |
| 178 | + newOp.resolve(null, that.data[0]); |
| 179 | + } else { |
| 180 | + for (var i = 0; i < that.options.maxWorkers && i < Math.floor(that.data.length / 2); ++i) { |
| 181 | + that._spawnReduceWorker([that.data[i * 2], that.data[i * 2 + 1]], cb, done); |
| 182 | + } |
| 183 | + |
| 184 | + that.data.splice(0, i * 2); |
| 185 | + } |
| 186 | + }); |
| 187 | + this.operation = newOp; |
| 188 | + return this; |
| 189 | + }; |
| 190 | + |
147 | 191 | Parallel.prototype.then = function (cb, errCb) { |
148 | 192 | var that = this; |
149 | 193 | var newOp = new Operation(); |
|
0 commit comments