Files
reverse-engineering-anything/src/domain/boundedList.ts
T
morluto 673050f7bc refactor(domain): bound a first batch of constant-maximum slices with boundedList (#11296)
* refactor(domain): bound a first batch of constant-maximum slices with boundedList

* fix(domain): describe a bounded list with nothing retained without a leading separator

* refactor(domain): bound eleven counted list samples through boundedList (#11421)

Desktop state differences, guidance subsection pointers, native output contract issues, APK v1 duplicate-name samples, environment write refusals, desktop build action logs and credential-named saved-value pointers already reported a count or a cut beside a sliced list; the slice and the count now come from one boundedList. constant-maximum-slice: 54 -> 43.
2026-11-16 04:24:58 +08:00

60 lines
1.6 KiB
TypeScript

/**
* Items retained up to a maximum, with how many more were offered. A bounded
* list never drops an item without counting it, so a consumer can always say
* that more exist and how many.
*/
export interface BoundedList<T> {
readonly items: readonly T[];
readonly omitted: number;
}
/**
* Retain the first `maximum` items and count the rest, adding to `omitted`
* items an earlier bound already left out.
*/
export const boundedList = <T>(
items: readonly T[],
maximum: number,
omitted = 0,
): BoundedList<T> => ({
items: items.slice(0, maximum),
omitted: omitted + Math.max(0, items.length - maximum),
});
/** Collects items up to a maximum and counts each item offered past it. */
export class BoundedListCollector<T> {
readonly #items: T[] = [];
#omitted = 0;
constructor(readonly maximum: number) {}
push(item: T): void {
if (this.#items.length < this.maximum) this.#items.push(item);
else this.#omitted += 1;
}
/** Whether a retained item equals `item`; omitted items are not kept. */
retains(item: T): boolean {
return this.#items.includes(item);
}
toList(): BoundedList<T> {
return { items: [...this.#items], omitted: this.#omitted };
}
}
/**
* The retained items joined by `separator`, then "and N more" for the omitted
* ones: `a; b; and 3 more`.
*/
export const describeBoundedList = (
list: BoundedList<string>,
separator: string,
): string => {
if (list.omitted === 0) return list.items.join(separator);
const rest = `and ${String(list.omitted)} more`;
return list.items.length === 0
? rest
: `${list.items.join(separator)}${separator}${rest}`;
};