Urgent.News

What's breaking now, across thousands of outlets.

Tech

Two scrolling panes is the wrong way to build a side-by-side diff

I had a text-compare tool that asked people to compare two things it would not show them at the same time. One textarea, then another textarea underneath it, then a single-column unified diff below that — removals in red, additions in green, in the order a diff algorithm emits them. Everything on the page was correct and the tool was close to useless, because comparing is a thing your eyes do in…

Comparing two pieces of text side-by-side in a single column is an ineffective approach for a text-compare tool. The reason lies in the way humans process information; our eyes naturally work in parallel, making side-by-side comparison more intuitive. By rearranging the layout into two columns, the tool becomes serial, rendering it close to useless.

The original text is divided into a flat list of line-level diffs using a longest-common-subsequence backtrack. Each entry describes whether a line is identical, deleted, or added. This flat list is then intended for a unified view, which presents the differences in a single column. However, a side-by-side view requires a different approach, as an edited line produces both a deletion and an addition, which may be spread apart within the list.

When rendering the diff into two columns, the removal and addition of a line can be several rows apart due to the algorithm's tendency to emit runs of removals followed by runs of additions. This misalignment makes the side-by-side view less effective than the unified view, as the elements being compared are not in the same positions on each side.

To address this issue, a function called sideBySide is introduced to reorganize the diff into a more suitable format for a side-by-side comparison. The function processes the diff list, grouping consecutive non-same entries into blocks and pairing them up index by index. The line numbers are counted separately for each side, which is crucial for accurately representing the differences.

The function handles three types of changes: unchanged lines, deleted lines, and added lines. For blocks of consecutive unchanged lines, the function simply pairs the corresponding lines from both sides. When encountering deletions and additions, the function separates them into distinct arrays and processes them individually. Finally, the function returns an array of objects representing the side-by-side diff, with each object indicating the type of change (same, del, add, or chg) along with the corresponding line numbers and actual lines.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Wednesday 12 August →