Files
reverse-engineering-anything/src/domain/analysisView/selectViewRows.ts
T

76 lines
2.7 KiB
TypeScript

/** An omitted filter admits every value; an empty filter admits none. */
export const filterSet = <Value>(values: readonly Value[] | undefined) =>
values === undefined ? undefined : new Set(values);
/** Keep explicit candidates within the collection, in original row order. */
export const orderedViewRowIndices = (
rowCount: number,
candidateIndices: ReadonlySet<number>,
): number[] => {
const ordered: number[] = [];
for (const index of candidateIndices) {
if (Number.isInteger(index) && index >= 0 && index < rowCount)
ordered.push(index);
}
return ordered.sort((left, right) => left - right);
};
/** Preserve original indices and count every match while projecting only the requested page. */
export const selectViewRows = <Source, Row>(
rows: readonly Source[],
view: { readonly offset: number; readonly limit: number },
matches: ((row: Source, index: number) => boolean) | undefined,
project: (row: Source, index: number) => Row,
candidateIndices?: ReadonlySet<number>,
): { rows: Row[]; total: number } => {
const ordered =
candidateIndices === undefined
? undefined
: orderedViewRowIndices(rows.length, candidateIndices);
const count = ordered?.length ?? rows.length;
const selected: Row[] = [];
if (matches === undefined) {
const start = Math.max(0, view.offset);
const end = Math.min(count, start + Math.max(0, view.limit));
for (let position = start; position < end; position += 1) {
const index = ordered?.[position] ?? position;
selected.push(project(rows[index]!, index));
}
return { rows: selected, total: count };
}
let total = 0;
for (let position = 0; position < count; position += 1) {
const index = ordered?.[position] ?? position;
const row = rows[index]!;
if (!matches(row, index)) continue;
if (total >= view.offset && selected.length < view.limit)
selected.push(project(row, index));
total++;
}
return { rows: selected, total };
};
/** Copy only own properties named in `fields` without allocating `Object.entries(row)`. */
export const pickFields = <Row extends Record<string, unknown>>(
row: Row,
fields: Iterable<string>,
): Record<string, unknown> => {
const picked: Record<string, unknown> = {};
for (const field of fields) {
if (Object.hasOwn(row, field)) picked[field] = row[field];
}
return picked;
};
/** Select own row fields in source order. An omitted selection copies the row. */
export const pickSourceOrderedFields = <T extends object>(
row: T,
fields: ReadonlySet<string> | undefined,
): Partial<T> => {
if (fields === undefined) return { ...row };
const out: Partial<T> = {};
for (const key of Object.keys(row) as (keyof T)[])
if (fields.has(String(key))) out[key] = row[key];
return out;
};