From 540699b682ae45d5d63679cc4d9171bf655d065c Mon Sep 17 00:00:00 2001 From: Mihai Ciuraru Date: Wed, 11 Sep 2019 21:36:35 +0300 Subject: [PATCH] Allow Enumerable to be initialized from iterable object --- linq.js | 13 +++++++++++++ package.json | 2 +- test/iterator.js | 45 ++++++++++++++++++++++++++++++++------------- 3 files changed, 46 insertions(+), 14 deletions(-) diff --git a/linq.js b/linq.js index 6fb19b9..b0d05ff 100644 --- a/linq.js +++ b/linq.js @@ -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 () { diff --git a/package.json b/package.json index 68e797a..97608f2 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "linq", "author": "Mihai Ciuraru ", "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", diff --git a/test/iterator.js b/test/iterator.js index ba0f8e6..228ef56 100644 --- a/test/iterator.js +++ b/test/iterator.js @@ -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)); +}); -} \ No newline at end of file +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"]); +});