Skip to content

Commit

Permalink
Allow functions returning an iterator to be used as input
Browse files Browse the repository at this point in the history
  • Loading branch information
mihaifm committed Nov 16, 2022
1 parent c93deb4 commit 45a45fb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions linq.js
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,22 @@ Enumerable.from = function (obj) {
Functions.Blank);
});
}
if (typeof obj == Types.Function && Object.keys(obj).length == 0) {
return new Enumerable(function () {
var orig;

return new IEnumerator(
function () {
orig = obj()[Symbol.iterator]();
},
function () {
var next = orig.next();
return (next.done ? false : (this.yieldReturn(next.value)));
},
Functions.Blank);
});
}

if (typeof obj != Types.Function) {
// array or array-like object
if (typeof obj.length == Types.Number) {
Expand Down
19 changes: 19 additions & 0 deletions test/iterator.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,22 @@ test("from Iterable", function () {
}
deepEqual(actual, ["abc", "def"]);
});

test("reusable iterator", function () {
const set = new Set([1, 2, 3])

let a = Enumerable.from(set.entries());

deepEqual(a.toArray(), [[1, 1], [2, 2], [3, 3]]);
deepEqual(a.toArray(), []);

let b = Enumerable.from(() => set.entries());

deepEqual(b.toArray(), [[1, 1], [2, 2], [3, 3]]);
deepEqual(b.toArray(), [[1, 1], [2, 2], [3, 3]]);

let c = Enumerable.from(() => ['x', 'y', 'z']);

deepEqual(c.toArray(), ['x', 'y', 'z']);
deepEqual(c.toArray(), ['x', 'y', 'z']);
});

0 comments on commit 45a45fb

Please sign in to comment.