Skip to content

Commit

Permalink
Fix histogram(iterable).
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed Dec 28, 2018
1 parent 2893908 commit db517b4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/histogram.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,18 @@ export default function() {
threshold = sturges;

function histogram(data) {
if (!Array.isArray(data)) data = Array.from(data);

var i,
n = data.length,
x,
values = Array.from(data, value),
xz = domain(values),
values = new Array(n);

for (i = 0; i < n; ++i) {
values[i] = value(data[i], i, data);
}

var xz = domain(values),
x0 = xz[0],
x1 = xz[1],
tz = threshold(values, x0, x1);
Expand Down
15 changes: 15 additions & 0 deletions test/histogram-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ tape("histogram(data) computes a histogram of the specified array of data", func
test.end();
});

tape("histogram(iterable) is equivalent to histogram(array)", function(test) {
var h = arrays.histogram();
test.deepEqual(h(iterable([0, 0, 0, 10, 20, 20])), [
bin([0, 0, 0], 0, 5),
bin([], 5, 10),
bin([10], 10, 15),
bin([20, 20], 15, 20) // Note: inclusive upper bound for last bin.
]);
test.end();
});

tape("histogram.value(number) sets the constant value", function(test) {
var h = arrays.histogram().value(12); // Pointless, but for consistency.
test.deepEqual(h([0, 0, 0, 1, 2, 2]), [
Expand Down Expand Up @@ -139,3 +150,7 @@ function bin(bin, x0, x1) {
bin.x1 = x1;
return bin;
}

function* iterable(array) {
yield* array;
}

0 comments on commit db517b4

Please sign in to comment.