Apply a style to a character range in run-length style runs
A code editor stores syntax highlighting as runs: a list of { length, style } objects that cover the text from left to right, one after another, with no gaps. The first run covers the first length characters, the next run continues where it stopped, and so on. style is a string such as 'keyword', or null for plain text.
// const total = 0;
const runs = [
{ length: 5, style: 'keyword' }, // 'const' indexes 0-4
{ length: 1, style: null }, // ' ' index 5
{ length: 5, style: 'variable' }, // 'total' indexes 6-10
{ length: 3, style: null }, // ' = ' indexes 11-13
{ length: 1, style: 'number' }, // '0' index 14
{ length: 1, style: null }, // ';' index 15
];
When the linter reports a problem, or the user selects text and clears its formatting, a range of characters gets a new style that overwrites whatever was there. Implement paintRuns(runs, start, end, style). It returns a new list of runs where every character from start (inclusive) to end (exclusive) has style, and every other character keeps its style.
paintRuns(runs, start, end, style) // => runs
start and end are integers. Clamp each of them to the range 0 to the text length.start >= end after clamping, no character is painted.style is a string or null. Styles are equal when they are ===.length: 0 and neighbouring runs with the same style.length: 0;runs or its objects.// Underline 'total' as an error.
paintRuns(runs, 6, 11, 'error');
// => [{ length: 5, style: 'keyword' }, { length: 1, style: null },
// { length: 5, style: 'error' }, { length: 3, style: null },
// { length: 1, style: 'number' }, { length: 1, style: null }]
// Clear formatting of 'st t' (indexes 3-6). The plain characters merge into one run.
paintRuns(runs, 3, 7, null);
// => [{ length: 3, style: 'keyword' }, { length: 4, style: null },
// { length: 4, style: 'variable' }, { length: 3, style: null },
// { length: 1, style: 'number' }, { length: 1, style: null }]
// Clear the number: ' = 0;' becomes one plain run.
paintRuns(runs, 14, 15, null);
// => [{ length: 5, style: 'keyword' }, { length: 1, style: null },
// { length: 5, style: 'variable' }, { length: 5, style: null }]
// Out-of-range indexes are clamped; the whole line becomes a comment.
paintRuns(runs, -10, 100, 'comment');
// => [{ length: 16, style: 'comment' }]
// Nothing painted, but the input is still normalized.
paintRuns([{ length: 2, style: 'a' }, { length: 0, style: 'b' }, { length: 3, style: 'a' }], 4, 1, 'x');
// => [{ length: 5, style: 'a' }]
paintRuns([], 0, 3, 'error'); // => []