-
-
Notifications
You must be signed in to change notification settings - Fork 143
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fa7b05c
commit 33512ec
Showing
1 changed file
with
53 additions
and
0 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import type { Predicate2 } from "@thi.ng/api"; | ||
|
||
/** | ||
* Takes an array of numbers and returns the index of the item which is | ||
* considered the minimum value according to the given initial `min` value | ||
* (default: ∞) and predicate (both optional). Returns -1 if `items` is empty. | ||
* | ||
* @remarks | ||
* See {@link argMax}. | ||
* | ||
* @example | ||
* ```ts | ||
* argMin([42, 11, 66, 23]) | ||
* // 1 | ||
* | ||
* // same as argmax() with defaults | ||
* argMin([42, 11, 66, 23], -Infinity, (a, b) => a > b) | ||
* // 2 | ||
* ``` | ||
* | ||
* @param buf | ||
* @param min | ||
* @param pred | ||
*/ | ||
export const argMin = ( | ||
buf: ArrayLike<number>, | ||
min = Infinity, | ||
pred: Predicate2<number> = (a, b) => a < b | ||
) => { | ||
let id = -1; | ||
for (let i = 0, n = buf.length; i < n; i++) { | ||
const x = buf[i]; | ||
if (pred(x, min)) { | ||
min = x; | ||
id = i; | ||
} | ||
} | ||
return id; | ||
}; | ||
|
||
/** | ||
* Similar to {@link argMin}, but selects index of maximum item. Returns -1 if | ||
* `items` is empty. | ||
* | ||
* @param items | ||
* @param min | ||
* @param pred | ||
*/ | ||
export const argMax = ( | ||
items: ArrayLike<number>, | ||
min = -Infinity, | ||
pred: Predicate2<number> = (a, b) => a > b | ||
) => argMin(items, min, pred); |