@harperfast/extended-iterable 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +95 -0
  3. package/index.d.ts +13 -0
  4. package/index.js +434 -0
  5. package/package.json +34 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,95 @@
1
+ [![license](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
2
+ [![npm version](https://img.shields.io/npm/v/extended-iterable.svg?style=flat-square)](https://www.npmjs.org/package/extended-iterable)
3
+ [![npm downloads](https://img.shields.io/npm/dw/extended-iterable)](https://www.npmjs.org/package/extended-iterable)
4
+
5
+ The extended-iterable package provides a class that implements the Iterable/Iterator protocol and provides array-like methods
6
+ with lazy evaluation, similar to [iterators helpers](https://github.com/tc39/proposal-iterator-helpers). However,
7
+ extended-iterable provides additional methods, the ability to handle both sync and async iteration, automatic handling of
8
+ asynchronous callbacks, and return/throw forwarding which can be critical for proper cleanup when used with
9
+ database transactions.
10
+
11
+ The package exports a single `ExtendedIterable` class, which can be constructed with a basic iterable or can be constructed
12
+ with no arguments and assigned (or overridden with) an `iterate` method that returns an iterator.
13
+
14
+ For example, we can create an `ExtendedIterable`:
15
+ ```javascript
16
+ import { ExtendedIterable } from '@harperdb/extended-iterable';
17
+
18
+ function performQuery() {
19
+ let results = new ExtendedIterable();
20
+ results.iterate = function() {
21
+ let txn = startTxn(); // we can start a transaction in some database, and be notified of when the iterable is completed below
22
+ let cursor = txn.doQuery();
23
+ return {
24
+ // implement an iterator
25
+ next() {
26
+ // iterate through a query or table
27
+ let entry = cursor.getNext();
28
+ if (entry)
29
+ return { value: entry };
30
+ else
31
+ return { done: true };
32
+ },
33
+ return () { // called when the iterator is done
34
+ txn.commit();
35
+ },
36
+ throw () {
37
+ txn.abort();
38
+ }
39
+ }
40
+ };
41
+ return results;
42
+ }
43
+ ```
44
+
45
+
46
+ The returned `ExtendedIterable` is fully iterable:
47
+
48
+ ```js
49
+ let extendedIterable = performQuery();
50
+ for (let value of extendedIterable) {
51
+ // for each value
52
+ }
53
+ ```
54
+
55
+ Or we can use the provided iterative methods on the returned results:
56
+
57
+ ```js
58
+ extendedIterable
59
+ .filter((value) => test(value))
60
+ .forEach((value) => {
61
+ // for each value that matched the filter
62
+ })
63
+ ```
64
+
65
+ Note that `map` and `filter` are also lazy, they will only be executed once their returned iterable is iterated or `forEach` is called on it. The `map` and `filter` functions also support async/promise-based functions, and you can create an async iterable if the callback functions execute asynchronously (return a promise).
66
+
67
+ We can also query with offset to skip a certain number of entries, and limit the number of entries to iterate through:
68
+
69
+ ```js
70
+ let sliced = extendedIterable.slice(10, 20); // skip first 10 and get next 10
71
+ ```
72
+
73
+ If you want to get a true array from the results, the `asArray` property will return the results as an array.
74
+
75
+ ### Catching Errors in iteration
76
+ With an array, `map` and `filter` callbacks are immediately executed, but wit iterators, they are executed during iteration, so if an error occurs during iteration, the error will be thrown when the iteration is attempted. It is also critical that when an iteration is finished, the cursor is closed, so by default, if an error occurs during iteration, the cursor will immediately be closed. However, if you want to catch errors that occur in `map` (and `flatMap`) callbacks during iteration, you can use the `mapError` method to catch errors that occur during iteration, and allow iteration to continue (without closing the cursor). For example:
77
+
78
+ ```js
79
+ let mapped = extendedIterable.map(({ key, value }) => {
80
+ return thisMightThrowError(value);
81
+ }).mapError((error) => {
82
+ // rather than letting the error terminate the iteration, we can catch it here and return a value to continue iterating:
83
+ return 'error occurred';
84
+ })
85
+ for (let entry of mapped) {
86
+ ...
87
+ }
88
+ ```
89
+ A `mapError` callback can return a value to continue iterating, or throw an error to terminate the iteration.
90
+
91
+ ## License
92
+
93
+ This library is licensed under the terms of the MIT license.
94
+
95
+ ## Related Projects
package/index.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export class ExtendedIterable<T> implements Iterable<T> {
2
+ concat(secondIterable: Iterable<T>): ExtendedIterable<T>;
3
+ new(sourceArray: Iterable<T>): ExtendedIterable<T>;
4
+ map<U>(callback: (entry: T, index: number) => U): ExtendedIterable<U>
5
+ flatMap<U>(callback: (entry: T, index: number) => U[]): ExtendedIterable<U>
6
+ slice(start: number, end: number): ExtendedIterable<T>
7
+ filter(callback: (entry: T, index: number) => any): ExtendedIterable<T>
8
+ [Symbol.iterator]() : Iterator<T>
9
+ forEach(callback: (entry: T, index: number) => any): void
10
+ mapError<U>(callback: (error: Error) => U): ExtendedIterable<U>
11
+ onDone?: Function
12
+ asArray: T[]
13
+ }
package/index.js ADDED
@@ -0,0 +1,434 @@
1
+ export const SKIP = Symbol.for('@harperdb/extended-iterable: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
+
16
+ export class ExtendedIterable {
17
+ constructor(sourceArray) {
18
+ if (sourceArray) {
19
+ this.iterate = sourceArray[Symbol.iterator].bind(sourceArray);
20
+ }
21
+ }
22
+ map(func) {
23
+ let source = this;
24
+ let iterable = new ExtendedIterable();
25
+ iterable.iterate = (options = NO_OPTIONS) => {
26
+ const { async } = options;
27
+ let iterator =
28
+ source[async ? Symbol.asyncIterator : Symbol.iterator](options);
29
+ if (!async) source.isSync = true;
30
+ let i = -1;
31
+ return {
32
+ next(resolvedResult) {
33
+ let result;
34
+ do {
35
+ let iteratorResult;
36
+ try {
37
+ if (resolvedResult) {
38
+ iteratorResult = resolvedResult;
39
+ resolvedResult = null; // don't go in this branch on next iteration
40
+ } else {
41
+ i++;
42
+ iteratorResult = iterator.next();
43
+ if (iteratorResult.then) {
44
+ if (!async) {
45
+ this.throw(
46
+ new Error(
47
+ 'Can not synchronously iterate with promises as iterator results',
48
+ ),
49
+ );
50
+ }
51
+ return iteratorResult.then(
52
+ (iteratorResult) => this.next(iteratorResult),
53
+ (error) => {
54
+ return this.throw(error);
55
+ },
56
+ );
57
+ }
58
+ }
59
+ if (iteratorResult.done === true) {
60
+ this.done = true;
61
+ if (iterable.onDone) iterable.onDone();
62
+ return iteratorResult;
63
+ }
64
+ try {
65
+ result = func.call(source, iteratorResult.value, i);
66
+ if (result && result.then && async) {
67
+ // if async, wait for promise to resolve before returning iterator result
68
+ return result.then(
69
+ (result) =>
70
+ result === SKIP
71
+ ? this.next()
72
+ : {
73
+ value: result,
74
+ },
75
+ (error) => {
76
+ if (options.continueOnRecoverableError)
77
+ error.continueIteration = true;
78
+ return this.throw(error);
79
+ },
80
+ );
81
+ }
82
+ } catch (error) {
83
+ // if the error came from the user function, we can potentially mark it for continuing iteration
84
+ if (options.continueOnRecoverableError)
85
+ error.continueIteration = true;
86
+ throw error; // throw to next catch to handle
87
+ }
88
+ } catch (error) {
89
+ if (iterable.handleError) {
90
+ // if we have handleError, we can use it to further handle errors
91
+ try {
92
+ result = iterable.handleError(error, i);
93
+ } catch (error2) {
94
+ return this.throw(error2);
95
+ }
96
+ } else return this.throw(error);
97
+ }
98
+ } while (result === SKIP);
99
+ if (result === DONE) {
100
+ return this.return();
101
+ }
102
+ return {
103
+ value: result,
104
+ };
105
+ },
106
+ return(value) {
107
+ if (!this.done) {
108
+ RETURN_DONE.value = value;
109
+ this.done = true;
110
+ if (iterable.onDone) iterable.onDone();
111
+ iterator.return?.();
112
+ }
113
+ return RETURN_DONE;
114
+ },
115
+ throw(error) {
116
+ if (error.continueIteration) {
117
+ // if it's a recoverable error, we can return or throw without closing the iterator
118
+ if (iterable.returnRecoverableErrors)
119
+ try {
120
+ return {
121
+ value: iterable.returnRecoverableErrors(error),
122
+ };
123
+ } catch (error) {
124
+ // if this throws, we need to go back to closing the iterator
125
+ this.return();
126
+ throw error;
127
+ }
128
+ if (options.continueOnRecoverableError) throw error; // throw without closing iterator
129
+ }
130
+ // else we are done with the iterator (and can throw)
131
+ this.return();
132
+ throw error;
133
+ },
134
+ };
135
+ };
136
+ return iterable;
137
+ }
138
+ [Symbol.asyncIterator](options) {
139
+ if (options) options = { ...options, async: true };
140
+ else options = { async: true };
141
+ return (this.iterator = this.iterate(options));
142
+ }
143
+ [Symbol.iterator](options) {
144
+ return (this.iterator = this.iterate(options));
145
+ }
146
+ filter(func) {
147
+ let iterable = this.map((element) => {
148
+ let result = func(element);
149
+ // handle promise
150
+ if (result?.then)
151
+ return result.then((result) => (result ? element : SKIP));
152
+ else return result ? element : SKIP;
153
+ });
154
+ let iterate = iterable.iterate;
155
+ iterable.iterate = (options = NO_OPTIONS) => {
156
+ // explicitly prevent continue on recoverable error with filter
157
+ if (options.continueOnRecoverableError)
158
+ options = { ...options, continueOnRecoverableError: false };
159
+ return iterate(options);
160
+ };
161
+ return iterable;
162
+ }
163
+
164
+ forEach(callback) {
165
+ let iterator = (this.iterator = this.iterate());
166
+ let result;
167
+ while ((result = iterator.next()).done !== true) {
168
+ callback(result.value);
169
+ }
170
+ }
171
+ concat(secondIterable) {
172
+ let concatIterable = new ExtendedIterable();
173
+ concatIterable.iterate = (options = NO_OPTIONS) => {
174
+ let iterator = (this.iterator = this.iterate(options));
175
+ let isFirst = true;
176
+ function iteratorDone(result) {
177
+ if (isFirst) {
178
+ try {
179
+ isFirst = false;
180
+ iterator =
181
+ secondIterable[
182
+ options.async ? Symbol.asyncIterator : Symbol.iterator
183
+ ]();
184
+ result = iterator.next();
185
+ if (concatIterable.onDone) {
186
+ if (result.then) {
187
+ if (!options.async)
188
+ throw new Error(
189
+ 'Can not synchronously iterate with promises as iterator results',
190
+ );
191
+ result.then(
192
+ (result) => {
193
+ if (result.done()) concatIterable.onDone();
194
+ },
195
+ (error) => {
196
+ this.return();
197
+ throw error;
198
+ },
199
+ );
200
+ } else if (result.done) concatIterable.onDone();
201
+ }
202
+ } catch (error) {
203
+ this.throw(error);
204
+ }
205
+ } else {
206
+ if (concatIterable.onDone) concatIterable.onDone();
207
+ }
208
+ return result;
209
+ }
210
+ return {
211
+ next() {
212
+ try {
213
+ let result = iterator.next();
214
+ if (result.then) {
215
+ if (!options.async)
216
+ throw new Error(
217
+ 'Can not synchronously iterate with promises as iterator results',
218
+ );
219
+ return result.then((result) => {
220
+ if (result.done) return iteratorDone(result);
221
+ return result;
222
+ });
223
+ }
224
+ if (result.done) return iteratorDone(result);
225
+ return result;
226
+ } catch (error) {
227
+ this.throw(error);
228
+ }
229
+ },
230
+ return(value) {
231
+ if (!this.done) {
232
+ RETURN_DONE.value = value;
233
+ this.done = true;
234
+ if (concatIterable.onDone) concatIterable.onDone();
235
+ iterator.return();
236
+ }
237
+ return RETURN_DONE;
238
+ },
239
+ throw(error) {
240
+ if (options.continueOnRecoverableError) throw error;
241
+ this.return();
242
+ throw error;
243
+ },
244
+ };
245
+ };
246
+ return concatIterable;
247
+ }
248
+
249
+ flatMap(callback) {
250
+ let mappedIterable = new ExtendedIterable();
251
+ mappedIterable.iterate = (options = NO_OPTIONS) => {
252
+ let iterator = (this.iterator = this.iterate(options));
253
+ let isFirst = true;
254
+ let currentSubIterator;
255
+ return {
256
+ next(resolvedResult) {
257
+ try {
258
+ do {
259
+ if (currentSubIterator) {
260
+ let result;
261
+ if (resolvedResult) {
262
+ result = resolvedResult;
263
+ resolvedResult = undefined;
264
+ } else result = currentSubIterator.next();
265
+ if (result.then) {
266
+ if (!options.async)
267
+ throw new Error(
268
+ 'Can not synchronously iterate with promises as iterator results',
269
+ );
270
+ return result.then((result) => this.next(result));
271
+ }
272
+ if (!result.done) {
273
+ return result;
274
+ }
275
+ }
276
+ let result;
277
+ if (resolvedResult != undefined) {
278
+ result = resolvedResult;
279
+ resolvedResult = undefined;
280
+ } else result = iterator.next();
281
+ if (result.then) {
282
+ if (!options.async)
283
+ throw new Error(
284
+ 'Can not synchronously iterate with promises as iterator results',
285
+ );
286
+ currentSubIterator = undefined;
287
+ return result.then((result) => this.next(result));
288
+ }
289
+ if (result.done) {
290
+ if (mappedIterable.onDone) mappedIterable.onDone();
291
+ return result;
292
+ }
293
+ try {
294
+ let value = callback(result.value);
295
+ if (value?.then) {
296
+ if (!options.async)
297
+ throw new Error(
298
+ 'Can not synchronously iterate with promises as iterator results',
299
+ );
300
+ return value.then(
301
+ (value) => {
302
+ if (
303
+ Array.isArray(value) ||
304
+ value instanceof ExtendedIterable
305
+ ) {
306
+ currentSubIterator = value[Symbol.iterator]();
307
+ return this.next();
308
+ } else {
309
+ currentSubIterator = null;
310
+ return { value };
311
+ }
312
+ },
313
+ (error) => {
314
+ if (options.continueOnRecoverableError)
315
+ error.continueIteration = true;
316
+ this.throw(error);
317
+ },
318
+ );
319
+ }
320
+ if (Array.isArray(value) || value instanceof ExtendedIterable)
321
+ currentSubIterator = value[Symbol.iterator]();
322
+ else {
323
+ currentSubIterator = null;
324
+ return { value };
325
+ }
326
+ } catch (error) {
327
+ if (options.continueOnRecoverableError)
328
+ error.continueIteration = true;
329
+ throw error;
330
+ }
331
+ } while (true);
332
+ } catch (error) {
333
+ this.throw(error);
334
+ }
335
+ },
336
+ return() {
337
+ if (mappedIterable.onDone) mappedIterable.onDone();
338
+ if (currentSubIterator) currentSubIterator.return();
339
+ return iterator.return();
340
+ },
341
+ throw(error) {
342
+ if (options.continueOnRecoverableError) throw error;
343
+ if (mappedIterable.onDone) mappedIterable.onDone();
344
+ if (currentSubIterator) currentSubIterator.return();
345
+ this.return();
346
+ throw error;
347
+ },
348
+ };
349
+ };
350
+ return mappedIterable;
351
+ }
352
+
353
+ slice(start, end) {
354
+ let iterable = this.map((element, i) => {
355
+ if (i < start) return SKIP;
356
+ if (i >= end) {
357
+ DONE.value = element;
358
+ return DONE;
359
+ }
360
+ return element;
361
+ });
362
+ iterable.handleError = (error, i) => {
363
+ if (i < start) return SKIP;
364
+ if (i >= end) {
365
+ return DONE;
366
+ }
367
+ throw error;
368
+ };
369
+ return iterable;
370
+ }
371
+ mapError(catch_callback) {
372
+ if (typeof catch_callback !== 'function') {
373
+ throw new TypeError('Expected catch callback to be a function');
374
+ }
375
+ let iterable = this.map((element) => {
376
+ return element;
377
+ });
378
+ let iterate = iterable.iterate;
379
+ iterable.iterate = (options = NO_OPTIONS) => {
380
+ // we need to ensure the whole stack
381
+ // of iterables is set up to handle recoverable errors and continue iteration
382
+ return iterate({ ...options, continueOnRecoverableError: true });
383
+ };
384
+ iterable.returnRecoverableErrors = catch_callback;
385
+ return iterable;
386
+ }
387
+ next() {
388
+ if (!this.iterator) this.iterator = this.iterate();
389
+ return this.iterator.next();
390
+ }
391
+ toJSON() {
392
+ if (this.asArray && this.asArray.forEach) {
393
+ return this.asArray;
394
+ }
395
+ const error = new Error(
396
+ 'Can not serialize async iterables without first calling resolving asArray',
397
+ );
398
+ error.resolution = this.asArray;
399
+ throw error;
400
+ //return Array.from(this)
401
+ }
402
+ get asArray() {
403
+ if (this._asArray) return this._asArray;
404
+ let promise = new Promise((resolve, reject) => {
405
+ let iterator = this.iterate(true);
406
+ let array = [];
407
+ let iterable = this;
408
+ Object.defineProperty(array, 'iterable', { value: iterable });
409
+ function next(result) {
410
+ while (result.done !== true) {
411
+ if (result.then) {
412
+ return result.then(next);
413
+ } else {
414
+ array.push(result.value);
415
+ }
416
+ result = iterator.next();
417
+ }
418
+ resolve((iterable._asArray = array));
419
+ }
420
+ next(iterator.next());
421
+ });
422
+ promise.iterable = this;
423
+ return this._asArray || (this._asArray = promise);
424
+ }
425
+ resolveData() {
426
+ return this.asArray;
427
+ }
428
+ at(index) {
429
+ for (let entry of this) {
430
+ if (index-- === 0) return entry;
431
+ }
432
+ }
433
+ }
434
+ ExtendedIterable.prototype.DONE = DONE;
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@harperfast/extended-iterable",
3
+ "author": "Harper",
4
+ "version": "1.0.1",
5
+ "description": "Extended iterable class, providing lazy array-like methods with automatic async and return/throw forwarding",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+ssh://git@github.com/harperdb/extended-iterable.git"
10
+ },
11
+ "keywords": [
12
+ "iterable",
13
+ "lazy"
14
+ ],
15
+ "scripts": {
16
+ "build": "rollup -c"
17
+ },
18
+ "type": "module",
19
+ "module": "./index.js",
20
+ "exports": {
21
+ ".": {
22
+ "import": "./index.js",
23
+ "require": "./dist/index.cjs"
24
+ }
25
+ },
26
+ "types": "./index.d.ts",
27
+ "files": [
28
+ "./index.js",
29
+ "./index.d.ts"
30
+ ],
31
+ "devDependencies": {
32
+ "rollup": "^4.53.3"
33
+ }
34
+ }