MCPcopy Create free account
hub / github.com/d3/d3-array / bin

Function bin

src/bin.js:10–125  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

8import sturges from "./threshold/sturges.js";
9
10export default function bin() {
11 var value = identity,
12 domain = extent,
13 threshold = sturges;
14
15 function histogram(data) {
16 if (!Array.isArray(data)) data = Array.from(data);
17
18 var i,
19 n = data.length,
20 x,
21 step,
22 values = new Array(n);
23
24 for (i = 0; i < n; ++i) {
25 values[i] = value(data[i], i, data);
26 }
27
28 var xz = domain(values),
29 x0 = xz[0],
30 x1 = xz[1],
31 tz = threshold(values, x0, x1);
32
33 // Convert number of thresholds into uniform thresholds, and nice the
34 // default domain accordingly.
35 if (!Array.isArray(tz)) {
36 const max = x1, tn = +tz;
37 if (domain === extent) [x0, x1] = nice(x0, x1, tn);
38 tz = ticks(x0, x1, tn);
39
40 // If the domain is aligned with the first tick (which it will by
41 // default), then we can use quantization rather than bisection to bin
42 // values, which is substantially faster.
43 if (tz[0] <= x0) step = tickIncrement(x0, x1, tn);
44
45 // If the last threshold is coincident with the domain’s upper bound, the
46 // last bin will be zero-width. If the default domain is used, and this
47 // last threshold is coincident with the maximum input value, we can
48 // extend the niced upper bound by one tick to ensure uniform bin widths;
49 // otherwise, we simply remove the last threshold. Note that we don’t
50 // coerce values or the domain to numbers, and thus must be careful to
51 // compare order (>=) rather than strict equality (===)!
52 if (tz[tz.length - 1] >= x1) {
53 if (max >= x1 && domain === extent) {
54 const step = tickIncrement(x0, x1, tn);
55 if (isFinite(step)) {
56 if (step > 0) {
57 x1 = (Math.floor(x1 / step) + 1) * step;
58 } else if (step < 0) {
59 x1 = (Math.ceil(x1 * -step) + 1) / -step;
60 }
61 }
62 } else {
63 tz.pop();
64 }
65 }
66 }
67

Callers 1

bin-test.jsFile · 0.90

Calls 1

constantFunction · 0.85

Tested by

no test coverage detected