pipecd icon indicating copy to clipboard operation
pipecd copied to clipboard

sortFunc never returns 0, so sorting reorders items with equal values

Open Ujjwal-Gowda opened this issue 3 months ago • 4 comments

What happened:

sortFunc in web/src/utils/common.ts never returns 0. When the two values are equal, a > b is false, so it falls through to the -1 branch:

export const sortFunc = (
  a: string | number,
  b: string | number,
  direction: "ASC" | "DESC" = "ASC"
): number => {
  if (direction === "ASC") return a > b ? 1 : -1;   // equal -> -1
  return a > b ? -1 : 1;                            // equal -> 1
};

So for identical inputs the comparator reports both a < b and b < a. Array.prototype.sort is only stable when the comparator returns 0 for equal elements, so equal elements get shuffled instead of keeping their original order.

What you expected to happen:

Equal values compare as equal (return 0) and keep their relative order.

How to reproduce it:

Sorting a list where several entries share a name:

const items = [
  { name: "api", id: 1 }, { name: "api", id: 2 }, { name: "api", id: 3 },
  { name: "api", id: 4 }, { name: "api", id: 5 }, { name: "api", id: 6 },
  { name: "web", id: 7 }, { name: "api", id: 8 }, { name: "api", id: 9 },
  { name: "api", id: 10 }, { name: "api", id: 11 }, { name: "api", id: 12 },
];
items.sort((a, b) => sortFunc(a.name, b.name)).map(i => i.id);
actual:   12,11,10,9,8,6,5,4,3,2,1,7
expected:  1,2,3,4,5,6,8,9,10,11,12,7

The equal-named entries come out fully reversed. The exact result also depends on list length, since V8 switches sorting strategy for larger arrays, so short lists can look fine while longer ones don't.

Where it shows up:

sortFunc sorts the piped/application lists in the four application forms (application-form-v0, application-form-v1, application-form-manual-v0, application-form-manual-v1) and in encrypt-secret-drawer, where duplicate names are normal. sortDateFunc calls sortFunc, so it has the same problem for equal timestamps.

web/src/utils/common.ts currently has no test file, which is probably why this went unnoticed.

Ujjwal-Gowda avatar Aug 13 '26 06:08 Ujjwal-Gowda

@Ujjwal-Gowda please assign me this issue

coder-Yash886 avatar Aug 14 '26 10:08 coder-Yash886

hi @Ahmad-Faraj if this issue is something which you guys would like to be implemented, I'll like to work on it

Prachi-Gupta2808 avatar Aug 31 '26 10:08 Prachi-Gupta2808

@Prachi-Gupta2808 I'm not a maintainer, so I can't assign it. That would need a maintainer.

Also @coder-Yash886 asked for this one back on Aug 14, so might be worth checking with them first.

Ahmad-Faraj avatar Aug 31 '26 18:08 Ahmad-Faraj

I'd like to work on this if no one is currently working on it.

iamrishu11 avatar Sep 24 '26 03:09 iamrishu11