iterate.com / docs

git clone https://git.iterate.com/repos/docs

docs / tests / merge.test.mjsmain at 8463f41

// merge.test.mjs — `node --test tests/merge.test.mjs`. The edits that take a commit into a
// doc's live text (processors/merge.ts `textEdits`): they give the new text, a small change is a
// small edit, and a large file costs milliseconds of CPU, not the seconds that ended the doc
// facet's invocation on /docs/config/AGENTS.md.
import { test } from "node:test";
import assert from "node:assert/strict";
import { textEdits } from "../processors/merge.ts";

/** `from` after `edits`, applied one by one as a `Y.Text` applies them. */
const applied = (from, edits) =>
  edits.reduce(
    (text, edit) =>
      "insert" in edit
        ? text.slice(0, edit.at) + edit.insert + text.slice(edit.at)
        : text.slice(0, edit.at) + text.slice(edit.at + edit.delete),
    from,
  );

test("a typo fixed in one line is an edit of that word, so a person typing in the same line keeps their keystrokes", () => {
  const from = "# Plan\n\nWe fly in on Wendesday.\n\n## Agenda\n";
  const to = "# Plan\n\nWe fly in on Wednesday.\n\n## Agenda\n";
  const edits = textEdits(from, to);
  assert.equal(applied(from, edits), to);
  assert.ok(edits.every((edit) => ("insert" in edit ? edit.insert.length : edit.delete) <= 2));
});

test("a commit that changes 50 places of a 30,000-character file costs milliseconds of CPU", () => {
  const lines = Array.from({ length: 400 }, (_, index) => `- line ${index}: ${"words ".repeat(9)}`);
  const from = lines.join("\n");
  const to = lines
    .flatMap((line, index) =>
      index % 8 === 0 ? [`- line ${index}, rewritten: ${"other words ".repeat(12)}`, ""] : [line],
    )
    .join("\n");
  const before = process.cpuUsage();
  const edits = textEdits(from, to);
  const spent = process.cpuUsage(before);
  assert.equal(applied(from, edits), to);
  assert.ok((spent.user + spent.system) / 1000 < 500);
});

test("lines replaced by wholly different text are replaced whole: the comparison by character has a bound", () => {
  const from = `intro\n${"a".repeat(3_000)}\noutro\n`;
  const to = `intro\n${"b".repeat(3_000)}\noutro\n`;
  const edits = textEdits(from, to);
  assert.equal(applied(from, edits), to);
  assert.deepEqual(edits, [
    { at: 6, delete: 3_001 },
    { at: 6, insert: `${"b".repeat(3_000)}\n` },
  ]);
});