Skip to content

Sort is not stable: equal lines change relative order, breaking diff readability #151

Description

@chirag127

Problem

The current sort implementation in vscode-sort-lines does not guarantee a stable sort for lines that compare as equal under the chosen sort mode. This means that after sorting, the relative order of duplicate lines is non-deterministic and may differ between VS Code versions (since the underlying Array.prototype.sort was not guaranteed stable before Node.js/V8 stabilised it in 2019, and the extension code does not enforce stability explicitly).

In practice, this causes unwanted noise in git diff when two people on different machines or VS Code versions sort the same file — the duplicate lines end up in a different order, producing a diff that looks like content changed when it semantically didn't.

Steps to Reproduce

  1. Create a file with duplicate lines in a non-trivial order:
    banana
    apple
    banana
    cherry
    apple
    
  2. Run "Sort Lines Ascending".
  3. Expected stable result:
    apple   (first occurrence)
    apple   (second occurrence)
    banana  (first occurrence)
    banana  (second occurrence)
    cherry
    
  4. Re-sort on a different machine / VS Code version — the two apple lines or two banana lines may swap, producing a diff.

Proposed Fix

Apply a stable sort by augmenting comparisons with the original line index as a tiebreaker:

const indexed = lines.map((line, i) => ({ line, i }));
indexed.sort((a, b) => {
  const cmp = compareLines(a.line, b.line); // existing comparison logic
  return cmp !== 0 ? cmp : a.i - b.i;      // tiebreak by original index = stable
});
return indexed.map(x => x.line);

This guarantees that the output is deterministic regardless of runtime sort stability.

Environment

  • VS Code: 1.89+
  • Extension: Tyriar.sort-lines latest

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions