Skip to content

Commit 88e56f3

Browse files
committed
Assert arrays passed to relativeComplement are sorted
1 parent 1d0a9ee commit 88e56f3

1 file changed

Lines changed: 28 additions & 6 deletions

File tree

src/compiler/core.ts

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -789,15 +789,37 @@ namespace ts {
789789
export function relativeComplement<T>(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: Comparer<T>): T[] | undefined {
790790
if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB;
791791
const result: T[] = [];
792-
outer: for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
793-
inner: for (; offsetA < arrayA.length; offsetA++) {
792+
loopB: for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
793+
if (offsetB > 0) {
794+
// Ensure `arrayB` is properly sorted.
795+
Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), Comparison.EqualTo);
796+
}
797+
798+
loopA: for (const startA = offsetA; offsetA < arrayA.length; offsetA++) {
799+
if (offsetA > startA) {
800+
// Ensure `arrayA` is properly sorted. We only need to perform this check if
801+
// `offsetA` has changed since we entered the loop.
802+
Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), Comparison.EqualTo);
803+
}
804+
794805
switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
795-
case Comparison.LessThan: break inner;
796-
case Comparison.EqualTo: continue outer;
797-
case Comparison.GreaterThan: continue inner;
806+
case Comparison.LessThan:
807+
// If B is less than A, B does not exist in arrayA. Add B to the result and
808+
// move to the next element in arrayB without changing the current position
809+
// in arrayA.
810+
result.push(arrayB[offsetB]);
811+
continue loopB;
812+
case Comparison.EqualTo:
813+
// If B is equal to A, B exists in arrayA. Move to the next element in
814+
// arrayB without adding B to the result or changing the current position
815+
// in arrayA.
816+
continue loopB;
817+
case Comparison.GreaterThan:
818+
// If B is greater than A, we need to keep looking for B in arrayA. Move to
819+
// the next element in arrayA and recheck.
820+
continue loopA;
798821
}
799822
}
800-
result.push(arrayB[offsetB]);
801823
}
802824
return result;
803825
}

0 commit comments

Comments
 (0)