RangeIterable.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. export const SKIP = {};
  2. const DONE = {
  3. value: null,
  4. done: true,
  5. };
  6. const RETURN_DONE = {
  7. // we allow this one to be mutated
  8. value: null,
  9. done: true,
  10. };
  11. if (!Symbol.asyncIterator) {
  12. Symbol.asyncIterator = Symbol.for('Symbol.asyncIterator');
  13. }
  14. const NO_OPTIONS = {};
  15. export class RangeIterable {
  16. constructor(sourceArray) {
  17. if (sourceArray) {
  18. this.iterate = sourceArray[Symbol.iterator].bind(sourceArray);
  19. }
  20. }
  21. map(func) {
  22. let source = this;
  23. let iterable = new RangeIterable();
  24. iterable.iterate = (options = NO_OPTIONS) => {
  25. const { async } = options;
  26. let iterator =
  27. source[async ? Symbol.asyncIterator : Symbol.iterator](options);
  28. if (!async) source.isSync = true;
  29. let i = -1;
  30. return {
  31. next(resolvedResult) {
  32. let result;
  33. do {
  34. let iteratorResult;
  35. try {
  36. if (resolvedResult) {
  37. iteratorResult = resolvedResult;
  38. resolvedResult = null; // don't go in this branch on next iteration
  39. } else {
  40. i++;
  41. iteratorResult = iterator.next();
  42. if (iteratorResult.then) {
  43. if (!async) {
  44. this.throw(
  45. new Error(
  46. 'Can not synchronously iterate with promises as iterator results',
  47. ),
  48. );
  49. }
  50. return iteratorResult.then(
  51. (iteratorResult) => this.next(iteratorResult),
  52. (error) => {
  53. return this.throw(error);
  54. },
  55. );
  56. }
  57. }
  58. if (iteratorResult.done === true) {
  59. this.done = true;
  60. if (iterable.onDone) iterable.onDone();
  61. return iteratorResult;
  62. }
  63. try {
  64. result = func.call(source, iteratorResult.value, i);
  65. if (result && result.then && async) {
  66. // if async, wait for promise to resolve before returning iterator result
  67. return result.then(
  68. (result) =>
  69. result === SKIP
  70. ? this.next()
  71. : {
  72. value: result,
  73. },
  74. (error) => {
  75. if (options.continueOnRecoverableError)
  76. error.continueIteration = true;
  77. return this.throw(error);
  78. },
  79. );
  80. }
  81. } catch (error) {
  82. // if the error came from the user function, we can potentially mark it for continuing iteration
  83. if (options.continueOnRecoverableError)
  84. error.continueIteration = true;
  85. throw error; // throw to next catch to handle
  86. }
  87. } catch (error) {
  88. if (iterable.handleError) {
  89. // if we have handleError, we can use it to further handle errors
  90. try {
  91. result = iterable.handleError(error, i);
  92. } catch (error2) {
  93. return this.throw(error2);
  94. }
  95. } else return this.throw(error);
  96. }
  97. } while (result === SKIP);
  98. if (result === DONE) {
  99. return this.return();
  100. }
  101. return {
  102. value: result,
  103. };
  104. },
  105. return(value) {
  106. if (!this.done) {
  107. RETURN_DONE.value = value;
  108. this.done = true;
  109. if (iterable.onDone) iterable.onDone();
  110. iterator.return();
  111. }
  112. return RETURN_DONE;
  113. },
  114. throw(error) {
  115. if (error.continueIteration) {
  116. // if it's a recoverable error, we can return or throw without closing the iterator
  117. if (iterable.returnRecoverableErrors)
  118. try {
  119. return {
  120. value: iterable.returnRecoverableErrors(error),
  121. };
  122. } catch (error) {
  123. // if this throws, we need to go back to closing the iterator
  124. this.return();
  125. throw error;
  126. }
  127. if (options.continueOnRecoverableError) throw error; // throw without closing iterator
  128. }
  129. // else we are done with the iterator (and can throw)
  130. this.return();
  131. throw error;
  132. },
  133. };
  134. };
  135. return iterable;
  136. }
  137. [Symbol.asyncIterator](options) {
  138. if (options) options = { ...options, async: true };
  139. else options = { async: true };
  140. return (this.iterator = this.iterate(options));
  141. }
  142. [Symbol.iterator](options) {
  143. return (this.iterator = this.iterate(options));
  144. }
  145. filter(func) {
  146. let iterable = this.map((element) => {
  147. let result = func(element);
  148. // handle promise
  149. if (result?.then)
  150. return result.then((result) => (result ? element : SKIP));
  151. else return result ? element : SKIP;
  152. });
  153. let iterate = iterable.iterate;
  154. iterable.iterate = (options = NO_OPTIONS) => {
  155. // explicitly prevent continue on recoverable error with filter
  156. if (options.continueOnRecoverableError)
  157. options = { ...options, continueOnRecoverableError: false };
  158. return iterate(options);
  159. };
  160. return iterable;
  161. }
  162. forEach(callback) {
  163. let iterator = (this.iterator = this.iterate());
  164. let result;
  165. while ((result = iterator.next()).done !== true) {
  166. callback(result.value);
  167. }
  168. }
  169. concat(secondIterable) {
  170. let concatIterable = new RangeIterable();
  171. concatIterable.iterate = (options = NO_OPTIONS) => {
  172. let iterator = (this.iterator = this.iterate(options));
  173. let isFirst = true;
  174. function iteratorDone(result) {
  175. if (isFirst) {
  176. try {
  177. isFirst = false;
  178. iterator =
  179. secondIterable[
  180. options.async ? Symbol.asyncIterator : Symbol.iterator
  181. ]();
  182. result = iterator.next();
  183. if (concatIterable.onDone) {
  184. if (result.then) {
  185. if (!options.async)
  186. throw new Error(
  187. 'Can not synchronously iterate with promises as iterator results',
  188. );
  189. result.then(
  190. (result) => {
  191. if (result.done()) concatIterable.onDone();
  192. },
  193. (error) => {
  194. this.return();
  195. throw error;
  196. },
  197. );
  198. } else if (result.done) concatIterable.onDone();
  199. }
  200. } catch (error) {
  201. this.throw(error);
  202. }
  203. } else {
  204. if (concatIterable.onDone) concatIterable.onDone();
  205. }
  206. return result;
  207. }
  208. return {
  209. next() {
  210. try {
  211. let result = iterator.next();
  212. if (result.then) {
  213. if (!options.async)
  214. throw new Error(
  215. 'Can not synchronously iterate with promises as iterator results',
  216. );
  217. return result.then((result) => {
  218. if (result.done) return iteratorDone(result);
  219. return result;
  220. });
  221. }
  222. if (result.done) return iteratorDone(result);
  223. return result;
  224. } catch (error) {
  225. this.throw(error);
  226. }
  227. },
  228. return(value) {
  229. if (!this.done) {
  230. RETURN_DONE.value = value;
  231. this.done = true;
  232. if (concatIterable.onDone) concatIterable.onDone();
  233. iterator.return();
  234. }
  235. return RETURN_DONE;
  236. },
  237. throw(error) {
  238. if (options.continueOnRecoverableError) throw error;
  239. this.return();
  240. throw error;
  241. },
  242. };
  243. };
  244. return concatIterable;
  245. }
  246. flatMap(callback) {
  247. let mappedIterable = new RangeIterable();
  248. mappedIterable.iterate = (options = NO_OPTIONS) => {
  249. let iterator = (this.iterator = this.iterate(options));
  250. let isFirst = true;
  251. let currentSubIterator;
  252. return {
  253. next(resolvedResult) {
  254. try {
  255. do {
  256. if (currentSubIterator) {
  257. let result;
  258. if (resolvedResult) {
  259. result = resolvedResult;
  260. resolvedResult = undefined;
  261. } else result = currentSubIterator.next();
  262. if (result.then) {
  263. if (!options.async)
  264. throw new Error(
  265. 'Can not synchronously iterate with promises as iterator results',
  266. );
  267. return result.then((result) => this.next(result));
  268. }
  269. if (!result.done) {
  270. return result;
  271. }
  272. }
  273. let result;
  274. if (resolvedResult != undefined) {
  275. result = resolvedResult;
  276. resolvedResult = undefined;
  277. } else result = iterator.next();
  278. if (result.then) {
  279. if (!options.async)
  280. throw new Error(
  281. 'Can not synchronously iterate with promises as iterator results',
  282. );
  283. currentSubIterator = undefined;
  284. return result.then((result) => this.next(result));
  285. }
  286. if (result.done) {
  287. if (mappedIterable.onDone) mappedIterable.onDone();
  288. return result;
  289. }
  290. try {
  291. let value = callback(result.value);
  292. if (value?.then) {
  293. if (!options.async)
  294. throw new Error(
  295. 'Can not synchronously iterate with promises as iterator results',
  296. );
  297. return value.then(
  298. (value) => {
  299. if (
  300. Array.isArray(value) ||
  301. value instanceof RangeIterable
  302. ) {
  303. currentSubIterator = value[Symbol.iterator]();
  304. return this.next();
  305. } else {
  306. currentSubIterator = null;
  307. return { value };
  308. }
  309. },
  310. (error) => {
  311. if (options.continueOnRecoverableError)
  312. error.continueIteration = true;
  313. this.throw(error);
  314. },
  315. );
  316. }
  317. if (Array.isArray(value) || value instanceof RangeIterable)
  318. currentSubIterator = value[Symbol.iterator]();
  319. else {
  320. currentSubIterator = null;
  321. return { value };
  322. }
  323. } catch (error) {
  324. if (options.continueOnRecoverableError)
  325. error.continueIteration = true;
  326. throw error;
  327. }
  328. } while (true);
  329. } catch (error) {
  330. this.throw(error);
  331. }
  332. },
  333. return() {
  334. if (mappedIterable.onDone) mappedIterable.onDone();
  335. if (currentSubIterator) currentSubIterator.return();
  336. return iterator.return();
  337. },
  338. throw(error) {
  339. if (options.continueOnRecoverableError) throw error;
  340. if (mappedIterable.onDone) mappedIterable.onDone();
  341. if (currentSubIterator) currentSubIterator.return();
  342. this.return();
  343. throw error;
  344. },
  345. };
  346. };
  347. return mappedIterable;
  348. }
  349. slice(start, end) {
  350. let iterable = this.map((element, i) => {
  351. if (i < start) return SKIP;
  352. if (i >= end) {
  353. DONE.value = element;
  354. return DONE;
  355. }
  356. return element;
  357. });
  358. iterable.handleError = (error, i) => {
  359. if (i < start) return SKIP;
  360. if (i >= end) {
  361. return DONE;
  362. }
  363. throw error;
  364. };
  365. return iterable;
  366. }
  367. mapError(catch_callback) {
  368. let iterable = this.map((element) => {
  369. return element;
  370. });
  371. let iterate = iterable.iterate;
  372. iterable.iterate = (options = NO_OPTIONS) => {
  373. // we need to ensure the whole stack
  374. // of iterables is set up to handle recoverable errors and continue iteration
  375. return iterate({ ...options, continueOnRecoverableError: true });
  376. };
  377. iterable.returnRecoverableErrors = catch_callback;
  378. return iterable;
  379. }
  380. next() {
  381. if (!this.iterator) this.iterator = this.iterate();
  382. return this.iterator.next();
  383. }
  384. toJSON() {
  385. if (this.asArray && this.asArray.forEach) {
  386. return this.asArray;
  387. }
  388. const error = new Error(
  389. 'Can not serialize async iterables without first calling resolving asArray',
  390. );
  391. error.resolution = this.asArray;
  392. throw error;
  393. //return Array.from(this)
  394. }
  395. get asArray() {
  396. if (this._asArray) return this._asArray;
  397. let promise = new Promise((resolve, reject) => {
  398. let iterator = this.iterate(true);
  399. let array = [];
  400. let iterable = this;
  401. Object.defineProperty(array, 'iterable', { value: iterable });
  402. function next(result) {
  403. while (result.done !== true) {
  404. if (result.then) {
  405. return result.then(next);
  406. } else {
  407. array.push(result.value);
  408. }
  409. result = iterator.next();
  410. }
  411. resolve((iterable._asArray = array));
  412. }
  413. next(iterator.next());
  414. });
  415. promise.iterable = this;
  416. return this._asArray || (this._asArray = promise);
  417. }
  418. resolveData() {
  419. return this.asArray;
  420. }
  421. at(index) {
  422. for (let entry of this) {
  423. if (index-- === 0) return entry;
  424. }
  425. }
  426. }
  427. RangeIterable.prototype.DONE = DONE;