@polygonjs/polygonjs
Version:
node-based WebGL 3D engine https://polygonjs.com
87 lines (86 loc) • 2.77 kB
JavaScript
"use strict";
import { Poly } from "../engine/Poly";
export class CoreIterator {
constructor(options = {}) {
this._array_index = 0;
// count
this._count = 0;
this._current_count_index = 0;
this._resolve = null;
this._max_time_per_chunk = options.max_time_per_chunk || 10;
this._check_every_interations = options.check_every_interations || 100;
}
async startWithCount(count, iteratee_method) {
this._count = count;
this._current_count_index = 0;
this._iteratee_method_count = iteratee_method;
this._bound_next_with_count = this.nextWithCount.bind(this);
if (this._resolve) {
throw "an iterator cannot be started twice";
}
return new Promise((resolve, reject) => {
this._resolve = resolve;
this.nextWithCount();
});
}
nextWithCount() {
const performance = Poly.performance.performanceManager();
const start_time = performance.now();
if (this._iteratee_method_count && this._bound_next_with_count) {
while (this._current_count_index < this._count) {
this._iteratee_method_count(this._current_count_index);
this._current_count_index++;
if (this._current_count_index % this._check_every_interations == 0) {
if (performance.now() - start_time > this._max_time_per_chunk) {
setTimeout(this._bound_next_with_count, 1);
break;
}
}
}
}
if (this._current_count_index >= this._count) {
if (this._resolve) {
this._resolve();
}
}
}
//
//
// ARRAY
//
//
async startWithArray(array, iteratee_method) {
this._array = array;
this._array_index = 0;
this._iteratee_method_array = iteratee_method;
this._bound_next_with_array = this.nextWithArray.bind(this);
if (this._resolve) {
throw "an iterator cannot be started twice";
}
return new Promise((resolve, reject) => {
this._resolve = resolve;
this.nextWithArray();
});
}
nextWithArray() {
const performance = Poly.performance.performanceManager();
const start_time = performance.now();
if (this._iteratee_method_array && this._bound_next_with_array && this._array) {
while (this._current_array_element = this._array[this._array_index]) {
this._iteratee_method_array(this._current_array_element, this._array_index);
this._array_index++;
if (this._array_index % this._check_every_interations == 0) {
if (performance.now() - start_time > this._max_time_per_chunk) {
setTimeout(this._bound_next_with_array, 1);
break;
}
}
}
}
if (this._current_array_element === void 0) {
if (this._resolve) {
this._resolve();
}
}
}
}