Skip to content

Commit da0edfe

Browse files
authored
fix(matrix): infinite loop (#6612)
1 parent d52729a commit da0edfe

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

packages/core/src/shared/object-matrix-query.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@
1414
* limitations under the License.
1515
*/
1616

17+
import type { IRange } from '../sheets/typedef';
18+
import type { Nullable } from './types';
1719
import { Range } from '../sheets/range';
1820
import { ObjectMatrix } from './object-matrix';
1921
import { Rectangle } from './rectangle';
20-
import type { IRange } from '../sheets/typedef';
21-
import type { Nullable } from './types';
2222

2323
function maximalRectangle<T>(matrix: T[][], match: (val: T) => boolean) {
2424
if (matrix.length === 0 || matrix[0].length === 0) return null;
@@ -90,14 +90,34 @@ function resetMatrix<T>(matrix: Nullable<T>[][], range: IRange) {
9090
*/
9191
export function queryObjectMatrix<T>(matrix: ObjectMatrix<T>, match: (value: T) => boolean) {
9292
const arrayMatrix = matrix.toFullArray();
93+
const rows = arrayMatrix.length;
94+
const cols = rows > 0 ? arrayMatrix[0].length : 0;
9395
const results: IRange[] = [];
94-
while (true) {
96+
97+
// Limit iterations to prevent excessive computation. Each iteration extracts at least
98+
// one maximal rectangle, so 1000 is a generous upper bound for practical use cases.
99+
const MAX_ITERATIONS = 1000;
100+
let iterations = 0;
101+
102+
while (iterations < MAX_ITERATIONS) {
103+
iterations++;
95104
const rectangle = maximalRectangle(arrayMatrix, match);
96105
if (!rectangle) {
97106
break;
98107
}
99108

100109
results.push(rectangle);
110+
111+
// If the rectangle covers the entire matrix, no need to continue.
112+
if (
113+
rectangle.startRow === 0 &&
114+
rectangle.startColumn === 0 &&
115+
rectangle.endRow === rows - 1 &&
116+
rectangle.endColumn === cols - 1
117+
) {
118+
break;
119+
}
120+
101121
resetMatrix(arrayMatrix, rectangle);
102122
}
103123

0 commit comments

Comments
 (0)