Skip to content

Commit

Permalink
Merge pull request #363 from jasondavies/extent
Browse files Browse the repository at this point in the history
Use single loop for d3.extent.
  • Loading branch information
mbostock committed Nov 4, 2011
2 parents 2b42dec + d11b5d9 commit a9043b9
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 6 deletions.
21 changes: 19 additions & 2 deletions d3.js
Expand Up @@ -106,8 +106,25 @@ d3.max = function(array, f) {
return a;
};
d3.extent = function(array, f) {
if (arguments.length > 1) array = array.map(f);
return [d3.min(array), d3.max(array)];
var i = -1,
n = array.length,
a,
b,
c;
if (arguments.length === 1) {
while (++i < n && ((a = c = array[i]) == null || a != a)) a = c = undefined;
while (++i < n) if ((b = array[i]) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
} else {
while (++i < n && ((a = c = f.call(array, array[i], i)) == null || a != a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
}
return [a, c];
};
d3.random = {
normal: function(mean, deviation) {
Expand Down
4 changes: 2 additions & 2 deletions d3.min.js

Large diffs are not rendered by default.

21 changes: 19 additions & 2 deletions src/core/extent.js
@@ -1,4 +1,21 @@
d3.extent = function(array, f) {
if (arguments.length > 1) array = array.map(f);
return [d3.min(array), d3.max(array)];
var i = -1,
n = array.length,
a,
b,
c;
if (arguments.length === 1) {
while (++i < n && ((a = c = array[i]) == null || a != a)) a = c = undefined;
while (++i < n) if ((b = array[i]) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
} else {
while (++i < n && ((a = c = f.call(array, array[i], i)) == null || a != a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
}
return [a, c];
};
1 change: 1 addition & 0 deletions test/core/extent-test.js
Expand Up @@ -26,6 +26,7 @@ suite.addBatch({
assert.deepEqual(extent([NaN, 1, 2, 3, 4, 5]), [1, 5]);
assert.deepEqual(extent([1, 2, 3, 4, 5, NaN]), [1, 5]);
assert.deepEqual(extent([10, null, 3, undefined, 5, NaN]), [3, 10]);
assert.deepEqual(extent([-1, null, -3, undefined, -5, NaN]), [-5, -1]);
},
"compares heterogenous types as numbers": function(extent) {
assert.deepEqual(extent([20, "3"]), ["3", 20]);
Expand Down

0 comments on commit a9043b9

Please sign in to comment.