refactor(common): simplify null/undefined check in keyvalue pipe (#59696)

In this commit, we remove the separate `a === undefined` and `a === null` checks and replace them with `a == null`. Using `a == null` is better and more concise because it checks for both `null` and `undefined` in a single operation. The loose equality `==` is specifically designed to treat `null` and `undefined` as equivalent. This change only reduces some bytes in the code and simplifies it, with no performance impact, as modern JavaScript engines handle `a == null` efficiently. Additionally, comments have been added for clarification.

PR Close #59696
This commit is contained in:
arturovt
2025-01-24 12:15:49 +02:00
committed by Pawel Kozlowski
parent 434568ba28
commit edb8407d4f
+9 -8
View File
@@ -132,25 +132,26 @@ export function defaultComparator<K, V>(
): number {
const a = keyValueA.key;
const b = keyValueB.key;
// if same exit with 0;
// If both keys are the same, return 0 (no sorting needed).
if (a === b) return 0;
// make sure that undefined are at the end of the sort.
if (a === undefined) return 1;
if (b === undefined) return -1;
// make sure that nulls are at the end of the sort.
if (a === null) return 1;
if (b === null) return -1;
// If one of the keys is `null` or `undefined`, place it at the end of the sort.
if (a == null) return 1; // `a` comes after `b`.
if (b == null) return -1; // `b` comes after `a`.
// If both keys are strings, compare them lexicographically.
if (typeof a == 'string' && typeof b == 'string') {
return a < b ? -1 : 1;
}
// If both keys are numbers, sort them numerically.
if (typeof a == 'number' && typeof b == 'number') {
return a - b;
}
// If both keys are booleans, sort `false` before `true`.
if (typeof a == 'boolean' && typeof b == 'boolean') {
return a < b ? -1 : 1;
}
// `a` and `b` are of different types. Compare their string values.
// Fallback case: if keys are of different types, compare their string representations.
const aString = String(a);
const bString = String(b);
// Compare the string representations lexicographically.
return aString == bString ? 0 : aString < bString ? -1 : 1;
}