CoverageCheck / web /src /lib /highlight.ts
TBM99's picture
Deploy coverage-check 3559250
23d418f verified
Raw History Blame Contribute Delete
948 Bytes
// Splitting an excerpt into plain and highlighted pieces from the server's spans.
export type Piece = { text: string; mark: boolean }
/** text cut at the spans ([start, end) character offsets, in order, as the server sends
* them): pieces alternate plain / marked; spans out of range or overlapping an earlier
* one are clipped, never thrown on (a highlight must not break the page). */
export function pieces(text: string, spans: [number, number][]): Piece[] {
const out: Piece[] = []
let at = 0
for (const [rawStart, rawEnd] of spans) {
const start = Math.max(at, Math.min(rawStart, text.length))
const end = Math.max(start, rawEnd) // slice() clamps an end past the text
if (start > at) out.push({ text: text.slice(at, start), mark: false })
if (end > start) out.push({ text: text.slice(start, end), mark: true })
at = end
}
if (at < text.length) out.push({ text: text.slice(at), mark: false })
return out
}