Skip to content

Commit 5cad183

Browse files
committed
fix: maxValue of bin may large than max, making empty bins
1 parent bf8dd4b commit 5cad183

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

packages/vdataset/__tests__/bin.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,13 @@ describe('bin transform', () => {
200200
expect(bins[9].x0).toBe(10);
201201
expect(bins[9].x1).toBe(11);
202202
});
203+
test('bins in max value and threshold 2', () => {
204+
const data = [1, 1, 1, 2, 5, 7, 8, 9, 10, 11, 12, 14].map(v => ({ v }));
205+
const bins = bin(data, { field: 'v', bins: 10 });
206+
expect(bins.length).toBe(7);
207+
expect(bins[6].x0).toBe(13);
208+
expect(bins[6].x1).toBe(15);
209+
});
203210

204211
test('bins in steps', () => {
205212
const data = [1, 1, 1, 2, 5, 7, 8, 9, 10].map(v => ({ v }));

packages/vdataset/src/transform/bin.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,20 +238,30 @@ export const bin: Transform = (data: Array<object>, options?: IBinOptions) => {
238238
}
239239
} else {
240240
// fallback to bins count (default 10)
241-
const bins = options.bins && options.bins > 0 ? Math.floor(options.bins) : 10;
241+
let bins = options.bins && options.bins > 0 ? Math.floor(options.bins) : 10;
242242
// If the data range is larger than 1, prefer integer thresholds when possible.
243243
if (max - min > 1) {
244244
const start = Math.floor(min);
245245
const stepSizeInt = Math.ceil((max - start) / bins);
246246
thresholds = new Array(bins + 1);
247247
for (let i = 0; i <= bins; i++) {
248248
thresholds[i] = start + stepSizeInt * i;
249+
if (thresholds[i] > max) {
250+
bins = i + 1;
251+
thresholds.length = bins;
252+
break;
253+
}
249254
}
250255
} else {
251256
const stepSize = (max - min) / bins;
252257
thresholds = new Array(bins + 1);
253258
for (let i = 0; i <= bins; i++) {
254259
thresholds[i] = min + stepSize * i;
260+
if (thresholds[i] > max) {
261+
bins = i + 1;
262+
thresholds.length = bins;
263+
break;
264+
}
255265
}
256266
}
257267
}

0 commit comments

Comments
 (0)