-
Notifications
You must be signed in to change notification settings - Fork 189
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
allow rank to take a comparator (#237)
* allow rank to take a comparator * another test, example
- Loading branch information
Showing
3 changed files
with
36 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,24 @@ | ||
import range from "./range.js"; | ||
import sort from "./sort.js"; | ||
import ascending from "./ascending.js"; | ||
import {ascendingDefined, compareDefined} from "./sort.js"; | ||
|
||
export default function rank(values, valueof) { | ||
export default function rank(values, valueof = ascending) { | ||
if (typeof values[Symbol.iterator] !== "function") throw new TypeError("values is not iterable"); | ||
values = Array.from(values, valueof); | ||
const n = values.length; | ||
const r = new Float64Array(n); | ||
let last, l; | ||
sort(range(n), (i) => values[i]).forEach((j, i) => { | ||
const value = values[j]; | ||
if (value == null || !(value <= value)) { | ||
r[j] = NaN; | ||
return; | ||
} | ||
if (last === undefined || !(value <= last)) { | ||
last = value; | ||
l = i; | ||
} | ||
r[j] = l; | ||
}); | ||
return r; | ||
let V = Array.from(values); | ||
const R = new Float64Array(V.length); | ||
if (valueof.length === 1) V = V.map(valueof), valueof = ascending; | ||
const compareIndex = (i, j) => valueof(V[i], V[j]); | ||
let k, r; | ||
Uint32Array | ||
.from(V, (_, i) => i) | ||
.sort(valueof === ascending ? (i, j) => ascendingDefined(V[i], V[j]) : compareDefined(compareIndex)) | ||
.forEach((j, i) => { | ||
const c = compareIndex(j, k === undefined ? j : k); | ||
if (c >= 0) { | ||
if (k === undefined || c > 0) k = j, r = i; | ||
R[j] = r; | ||
} else { | ||
R[j] = NaN; | ||
} | ||
}); | ||
return R; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters