Skip to content

Commit 45a45fb

Browse files
committed
Allow functions returning an iterator to be used as input
1 parent c93deb4 commit 45a45fb

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

linq.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,22 @@ Enumerable.from = function (obj) {
300300
Functions.Blank);
301301
});
302302
}
303+
if (typeof obj == Types.Function && Object.keys(obj).length == 0) {
304+
return new Enumerable(function () {
305+
var orig;
306+
307+
return new IEnumerator(
308+
function () {
309+
orig = obj()[Symbol.iterator]();
310+
},
311+
function () {
312+
var next = orig.next();
313+
return (next.done ? false : (this.yieldReturn(next.value)));
314+
},
315+
Functions.Blank);
316+
});
317+
}
318+
303319
if (typeof obj != Types.Function) {
304320
// array or array-like object
305321
if (typeof obj.length == Types.Number) {

test/iterator.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,22 @@ test("from Iterable", function () {
3535
}
3636
deepEqual(actual, ["abc", "def"]);
3737
});
38+
39+
test("reusable iterator", function () {
40+
const set = new Set([1, 2, 3])
41+
42+
let a = Enumerable.from(set.entries());
43+
44+
deepEqual(a.toArray(), [[1, 1], [2, 2], [3, 3]]);
45+
deepEqual(a.toArray(), []);
46+
47+
let b = Enumerable.from(() => set.entries());
48+
49+
deepEqual(b.toArray(), [[1, 1], [2, 2], [3, 3]]);
50+
deepEqual(b.toArray(), [[1, 1], [2, 2], [3, 3]]);
51+
52+
let c = Enumerable.from(() => ['x', 'y', 'z']);
53+
54+
deepEqual(c.toArray(), ['x', 'y', 'z']);
55+
deepEqual(c.toArray(), ['x', 'y', 'z']);
56+
});

0 commit comments

Comments
 (0)