Skip to content

Commit

Permalink
Implement for...of iterator via Symbol.iterator (#1197)
Browse files Browse the repository at this point in the history
* Implement for...of iterator via Symbol.iterator

Similar to jQuery: https://github.com/jquery/jquery/blob/1ea092a54b00aa4d902f4e22ada3854d195d4a18/src/core.js#L371-L373

Fixes #1191

* Assert that the iterator ends

#1197 (comment)
  • Loading branch information
papandreou authored and fb55 committed May 14, 2018
1 parent d26b392 commit f698a31
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/cheerio.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/*global Symbol*/
/*
Module dependencies
*/
Expand Down Expand Up @@ -138,6 +139,11 @@ Cheerio.prototype.toArray = function() {
return this.get();
};

// Support for (const element of $(...)) iteration:
if (typeof Symbol !== 'undefined') {
Cheerio.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
}

// Plug in the API
api.forEach(function(mod) {
_.extend(Cheerio.prototype, mod);
Expand Down
16 changes: 16 additions & 0 deletions test/api/traversing.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/*global Symbol*/
var expect = require('expect.js'),
cheerio = require('../..'),
food = require('../fixtures').food,
Expand Down Expand Up @@ -680,6 +681,21 @@ describe('$(...)', function() {
});
});

if (typeof Symbol !== 'undefined') {
describe('[Symbol.iterator]', function() {

it('should yield each element', function() {
// The equivalent of: for (const element of $('li')) ...
var $li = $('li'),
iterator = $li[Symbol.iterator]();
expect(iterator.next().value.attribs['class']).to.equal('apple');
expect(iterator.next().value.attribs['class']).to.equal('orange');
expect(iterator.next().value.attribs['class']).to.equal('pear');
expect(iterator.next().done).to.equal(true);
});
});
}

describe('.map', function() {
it('(fn) : should be invoked with the correct arguments and context', function() {
var $fruits = $('li');
Expand Down

0 comments on commit f698a31

Please sign in to comment.