/**
 * Returns the last count lines of out, each truncated to maxLineLength
 * characters, with an ellipsis if the line is truncated. Performance is almost
 * independent on out size, given that count is constant.
 */
export function lastLines(
  out: string,
  count: number,
  maxLineLength: number,
): string {
  const lines: string[] = [];
  let posNewline1 = out.lastIndexOf("\n");
  let posNewline2 = out.length;

  while (posNewline2 >= 0 && lines.length < count) {
    const line = out.substring(posNewline1 + 1, posNewline2).trimEnd();
    if (line.length > 0) {
      lines.unshift(
        line.length <= maxLineLength
          ? line
          : line.substring(0, maxLineLength - 1) + "…",
      );
    }

    posNewline2 = posNewline1;
    posNewline1 = out.lastIndexOf("\n", posNewline2 - 1);
  }

  return lines.join("\n");
}
