Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions heap.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
* Mnemonist Heap Typings
* =======================
*/
import {TypedArray} from './utils/types';

type HeapComparator<T> = (a: T, b: T) => number;

export default class Heap<T> {
Expand Down Expand Up @@ -90,7 +92,11 @@ export function pushpop<T>(comparator: HeapComparator<T>, heap: Array<T>, item:
export function heapify<T>(comparator: HeapComparator<T>, array: Array<T>): void;
export function consume<T>(comparator: HeapComparator<T>, heap: Array<T>): Array<T>;

export function nsmallest<T extends TypedArray>(comparator: HeapComparator<number>, n: number, values: T): ReturnType<T['slice']>;
export function nsmallest<T extends TypedArray>(n: number, values: T): ReturnType<T['slice']>;
export function nsmallest<T>(comparator: HeapComparator<T>, n: number, values: Iterable<T>): Array<T>;
export function nsmallest<T>(n: number, values: Iterable<T>): Array<T>;
export function nlargest<T extends TypedArray>(comparator: HeapComparator<number>, n: number, values: T): ReturnType<T['slice']>;
export function nlargest<T extends TypedArray>(n: number, values: T): ReturnType<T['slice']>;
export function nlargest<T>(comparator: HeapComparator<T>, n: number, values: Iterable<T>): Array<T>;
export function nlargest<T>(n: number, values: Iterable<T>): Array<T>;
14 changes: 14 additions & 0 deletions test/heap-selection-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {nsmallest, nlargest} from '../heap';

const input = new Uint16Array([4, 1, 3]);
const small: Uint16Array = nsmallest(2, input);
const large: Uint16Array = nlargest((a, b) => a - b, 2, input);
const floatSmall: Float32Array = nsmallest((a, b) => a - b, 1, new Float32Array([2, 1]));
const floatLarge: Float64Array = nlargest(1, new Float64Array([2, 1]));
const array: number[] = nsmallest(2, [4, 1, 3]);
const iterable: string[] = nlargest(1, new Set(['a', 'b']));
// @ts-expect-error Typed array selections are not JavaScript arrays.
const wrong: number[] = nsmallest(2, input);
// @ts-expect-error Numeric typed arrays need numeric comparators.
nlargest((a: string, b: string) => a.localeCompare(b), 2, input);
void [small, large, floatSmall, floatLarge, array, iterable, wrong];