Skip to content

Commit 540699b

Browse files
committed
Allow Enumerable to be initialized from iterable object
1 parent 102065d commit 540699b

File tree

3 files changed

+46
-14
lines changed

3 files changed

+46
-14
lines changed

linq.js

+13
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,19 @@
306306
return new ArrayEnumerable(obj);
307307
}
308308

309+
// iterable object
310+
if (typeof Symbol !== 'undefined' && typeof obj[Symbol.iterator] !== 'undefined') {
311+
return new Enumerable(function () {
312+
return new IEnumerator(
313+
Functions.Blank,
314+
function () {
315+
var next = obj.next();
316+
return (next.done ? false : (this.yieldReturn(next.value)));
317+
},
318+
Functions.Blank);
319+
});
320+
}
321+
309322
// JScript's IEnumerable
310323
if (!(obj instanceof Object) && Utils.isIEnumerable(obj)) {
311324
return new Enumerable(function () {

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "linq",
33
"author": "Mihai Ciuraru <[email protected]>",
44
"description": "linq.js - LINQ for JavaScript library packaged for node.js",
5-
"version": "3.2.0",
5+
"version": "3.2.1",
66
"homepage": "https://github.com/mihaifm/linq",
77
"repository": {
88
"type": "git",

test/iterator.js

+32-13
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,39 @@ var module = QUnit.module;
22
var Enumerable = require('../linq');
33
require("../extensions/linq.qunit.js")({'Enumerable': Enumerable});
44

5-
if (Enumerable.Utils.hasNativeIteratorSupport()) {
5+
module("Iterator");
66

7-
module("Iterator");
7+
var actual, expected;
88

9-
var actual, expected;
9+
test("for..of", function () {
10+
actual = [];
11+
for (var a of Enumerable.from([1, 2, 3])) {
12+
actual.push(a);
13+
}
14+
deepEqual(actual, [1, 2, 3]);
15+
});
1016

11-
test("for..of", function ()
12-
{
13-
actual = [1,2,3,4];
14-
expected = Array.from(Enumerable.from(actual));
15-
deepEqual(actual, expected);
16-
var actual2 = actual.map(function(x) { return x * 2 }); // [2,4,6,8];
17-
expected = Enumerable.from(actual).select(function(x) { return x * 2 });
18-
deepEqual(actual2, Array.from(expected));
19-
});
17+
test("Symbol.iterator", function ()
18+
{
19+
actual = [1,2,3,4];
20+
expected = Array.from(Enumerable.from(actual));
21+
deepEqual(actual, expected);
22+
var actual2 = actual.map(function(x) { return x * 2 }); // [2,4,6,8];
23+
expected = Enumerable.from(actual).select(function(x) { return x * 2 });
24+
deepEqual(actual2, Array.from(expected));
25+
});
2026

21-
}
27+
test("from Iterable", function () {
28+
function* words() {
29+
yield "abc";
30+
yield "def";
31+
}
32+
33+
deepEqual(Enumerable.from(words()).toArray(), ["abc", "def"]);
34+
35+
actual = [];
36+
for (var a of Enumerable.from(words())) {
37+
actual.push(a);
38+
}
39+
deepEqual(actual, ["abc", "def"]);
40+
});

0 commit comments

Comments
 (0)