Skip to content

Commit

Permalink
don’t invoke accessor more than once
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed May 30, 2023
1 parent a6fb8f4 commit 6477d93
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
18 changes: 9 additions & 9 deletions src/quantile.js
Expand Up @@ -34,14 +34,14 @@ export function quantileSorted(values, p, valueof = number) {

export function quantileIndex(values, p, valueof = number) {
if (isNaN(p = +p)) return;
if (p <= 0) return minIndex(values, valueof);
if (p >= 1) return maxIndex(values, valueof);
var index = Uint32Array.from(values, (_, i) => i),
j = index.length - 1,
i = Math.floor(j * p),
value = (i) => number(valueof(values[i], i, values)),
order = (i, j) => ascendingDefined(value(i), value(j));
quickselect(index, i, 0, j, order);
i = greatest(index.subarray(0, i + 1), value);
numbers = Float64Array.from(values, (_, i) => number(valueof(values[i], i, values)));
if (p <= 0) return minIndex(numbers);
if (p >= 1) return maxIndex(numbers);
var numbers,
index = Uint32Array.from(values, (_, i) => i),
j = numbers.length - 1,
i = Math.floor(j * p);
quickselect(index, i, 0, j, (i, j) => ascendingDefined(numbers[i], numbers[j]));
i = greatest(index.subarray(0, i + 1), (i) => numbers[i]);
return i >= 0 ? i : -1;
}
1 change: 1 addition & 0 deletions test/quantile-test.js
Expand Up @@ -119,6 +119,7 @@ it("quantileIndex(array, 1) returns the maximum index", () => {

it("quantileIndex(array, 0.5) handles undefined values", () => {
assert.deepStrictEqual(quantileIndex([1, 1, 1, null, 2, 3, 3, 3], 0.5), 4);
assert.deepStrictEqual(quantileIndex([1, 1, 1, null, 2, 3, 3, 3], 0.5, (d) => d), 4);
});

it("quantileIndex(array, 0.5) returns the first of equivalent values", () => {
Expand Down

0 comments on commit 6477d93

Please sign in to comment.