Skip to content

Commit

Permalink
Allow Enumerable to be initialized from iterable object
Browse files Browse the repository at this point in the history
  • Loading branch information
mihaifm committed Sep 11, 2019
1 parent 102065d commit 540699b
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 14 deletions.
13 changes: 13 additions & 0 deletions linq.js
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,19 @@
return new ArrayEnumerable(obj);
}

// iterable object
if (typeof Symbol !== 'undefined' && typeof obj[Symbol.iterator] !== 'undefined') {
return new Enumerable(function () {
return new IEnumerator(
Functions.Blank,
function () {
var next = obj.next();
return (next.done ? false : (this.yieldReturn(next.value)));
},
Functions.Blank);
});
}

// JScript's IEnumerable
if (!(obj instanceof Object) && Utils.isIEnumerable(obj)) {
return new Enumerable(function () {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "linq",
"author": "Mihai Ciuraru <mihaixc@gmail.com>",
"description": "linq.js - LINQ for JavaScript library packaged for node.js",
"version": "3.2.0",
"version": "3.2.1",
"homepage": "https://github.com/mihaifm/linq",
"repository": {
"type": "git",
Expand Down
45 changes: 32 additions & 13 deletions test/iterator.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,39 @@ var module = QUnit.module;
var Enumerable = require('../linq');
require("../extensions/linq.qunit.js")({'Enumerable': Enumerable});

if (Enumerable.Utils.hasNativeIteratorSupport()) {
module("Iterator");

module("Iterator");
var actual, expected;

var actual, expected;
test("for..of", function () {
actual = [];
for (var a of Enumerable.from([1, 2, 3])) {
actual.push(a);
}
deepEqual(actual, [1, 2, 3]);
});

test("for..of", function ()
{
actual = [1,2,3,4];
expected = Array.from(Enumerable.from(actual));
deepEqual(actual, expected);
var actual2 = actual.map(function(x) { return x * 2 }); // [2,4,6,8];
expected = Enumerable.from(actual).select(function(x) { return x * 2 });
deepEqual(actual2, Array.from(expected));
});
test("Symbol.iterator", function ()
{
actual = [1,2,3,4];
expected = Array.from(Enumerable.from(actual));
deepEqual(actual, expected);
var actual2 = actual.map(function(x) { return x * 2 }); // [2,4,6,8];
expected = Enumerable.from(actual).select(function(x) { return x * 2 });
deepEqual(actual2, Array.from(expected));
});

}
test("from Iterable", function () {
function* words() {
yield "abc";
yield "def";
}

deepEqual(Enumerable.from(words()).toArray(), ["abc", "def"]);

actual = [];
for (var a of Enumerable.from(words())) {
actual.push(a);
}
deepEqual(actual, ["abc", "def"]);
});

0 comments on commit 540699b

Please sign in to comment.