Skip to content

Commit

Permalink
Fix #197 iterable selections.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed Jul 29, 2019
1 parent 8fc76d7 commit 20029cb
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/selection/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import selection_clone from "./clone";
import selection_datum from "./datum";
import selection_on from "./on";
import selection_dispatch from "./dispatch";
import selection_iterator from "./iterator";

export var root = [null];

Expand Down Expand Up @@ -73,7 +74,8 @@ Selection.prototype = selection.prototype = {
clone: selection_clone,
datum: selection_datum,
on: selection_on,
dispatch: selection_dispatch
dispatch: selection_dispatch,
[Symbol.iterator]: selection_iterator
};

export default selection;
7 changes: 7 additions & 0 deletions src/selection/iterator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function*() {
for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
if (node = group[i]) yield node;
}
}
}
27 changes: 27 additions & 0 deletions test/selection/iterator-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
var tape = require("tape"),
jsdom = require("../jsdom"),
d3 = require("../../");

tape("selection are iterable over the selected nodes", function(test) {
var document = jsdom("<h1 id='one'></h1><h1 id='two'></h1>"),
one = document.querySelector("#one"),
two = document.querySelector("#two");
test.deepEqual([...d3.selectAll([one, two])], [one, two]);
test.end();
});

tape("selection iteration merges nodes from all groups into a single array", function(test) {
var document = jsdom("<h1 id='one'></h1><h1 id='two'></h1>"),
one = document.querySelector("#one"),
two = document.querySelector("#two");
test.deepEqual([...d3.selectAll([one, two]).selectAll(function() { return [this]; })], [one, two]);
test.end();
});

tape("selection iteration skips missing elements", function(test) {
var document = jsdom("<h1 id='one'></h1><h1 id='two'></h1>"),
one = document.querySelector("#one"),
two = document.querySelector("#two");
test.deepEqual([...d3.selectAll([, one,, two])], [one, two]);
test.end();
});

0 comments on commit 20029cb

Please sign in to comment.