Skip to content

Commit b632cf1

Browse files
committed
Coerce to number for d3.quantile.
This avoids string concatentation on fractional p-values.
1 parent 89c3e75 commit b632cf1

4 files changed

Lines changed: 20 additions & 10 deletions

File tree

d3.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@
234234
return s;
235235
};
236236
d3.quantile = function(values, p) {
237-
var H = (values.length - 1) * p + 1, h = Math.floor(H), v = values[h - 1], e = H - h;
237+
var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
238238
return e ? v + e * (values[h] - v) : v;
239239
};
240240
d3.shuffle = function(array) {

d3.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/core/quantile.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
d3.quantile = function(values, p) {
33
var H = (values.length - 1) * p + 1,
44
h = Math.floor(H),
5-
v = values[h - 1],
5+
v = +values[h - 1],
66
e = H - h;
77
return e ? v + e * (values[h] - v) : v;
88
};

test/core/quantile-test.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,18 +30,28 @@ suite.addBatch({
3030
assert.equal(quantile(data, .75), 14);
3131
assert.equal(quantile(data, 1), 20);
3232
},
33+
"coerces values to numbers": function(quantile) {
34+
var strings = ["1", "2", "3", "4"];
35+
assert.strictEqual(quantile(strings, 1/3), 2);
36+
assert.strictEqual(quantile(strings, 1/2), 2.5);
37+
assert.strictEqual(quantile(strings, 2/3), 3);
38+
var dates = [new Date(2011, 0, 1), new Date(2012, 0, 1)];
39+
assert.strictEqual(quantile(dates, 0), +new Date(2011, 0, 1));
40+
assert.strictEqual(quantile(dates, 1/2), +new Date(2011, 6, 2, 13));
41+
assert.strictEqual(quantile(dates, 1), +new Date(2012, 0, 1));
42+
},
3343
"returns an exact value for integer p-values": function(quantile) {
34-
var a = {}, b = {}, c = {}, d = {}, data = [a, b, c, d];
35-
assert.equal(quantile(data, 1/3), b);
36-
assert.equal(quantile(data, 2/3), c);
44+
var data = [1, 2, 3, 4];
45+
assert.equal(quantile(data, 1/3), 2);
46+
assert.equal(quantile(data, 2/3), 3);
3747
},
3848
"returns the first value for p = 0": function(quantile) {
39-
var a = {}, b = {}, c = {}, d = {}, data = [a, b, c, d];
40-
assert.equal(quantile(data, 0), a);
49+
var data = [1, 2, 3, 4];
50+
assert.equal(quantile(data, 0), 1);
4151
},
4252
"returns the last value for p = 1": function(quantile) {
43-
var a = {}, b = {}, c = {}, d = {}, data = [a, b, c, d];
44-
assert.equal(quantile(data, 1), d);
53+
var data = [1, 2, 3, 4];
54+
assert.equal(quantile(data, 1), 4);
4555
}
4656
}
4757
});

0 commit comments

Comments
 (0)