Skip to content

Commit

Permalink
[FIX] functions: FILTER with strings and errors
Browse files Browse the repository at this point in the history
The FILTER function should only consider numbers and booleans as the
conditions but it currently only accepts all types of values (strings, errors)
as long as the value is "truthy".

Steps to reproduce:

Let's consider this grid
	A	B
1     Alice  coucou
2      Bob    TRUE

The formula =FILTER(A1:A2, B1:B2) should only yield Bob and not Alice.

Note that this is a breaking change since the behavior is different.
That's why I'm not backporting the fix.

closes #5159

Task: 4307604
Signed-off-by: Rémi Rahir (rar) <[email protected]>
  • Loading branch information
LucasLefevre committed Nov 8, 2024
1 parent eb4c130 commit 03d7080
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/functions/module_filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,9 @@ export const FILTER = {
const result: Matrix<FunctionResultObject> = [];
for (let i = 0; i < _array.length; i++) {
const row = _array[i];
if (_conditions.every((c) => c[i])) {
if (
_conditions.every((c) => (typeof c[i] === "boolean" || typeof c[i] === "number") && c[i])
) {
result.push(row);
}
}
Expand Down
23 changes: 23 additions & 0 deletions tests/functions/module_filter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,17 @@ describe("FILTER function", () => {
expect(checkFunctionDoesntSpreadBeyondRange(model, "D1")).toBeTruthy();
});

test("FILTER by string ignores the value", () => {
// prettier-ignore
const grid = {
A1: "Alice", B1: "yes",
A2: "Bob", B2: "TRUE",
};
const model = createModelFromGrid(grid);
setCellContent(model, "A6", "=FILTER(A1:A2, B1:B2)");
expect(getRangeValuesAsMatrix(model, "A6:A7")).toEqual([["Bob"], [null]]);
});

test("FILTER accepts errors in first argument", () => {
// prettier-ignore
const grid = {
Expand All @@ -120,6 +131,18 @@ describe("FILTER function", () => {
setCellContent(model, "A6", "=FILTER(A1:A3, B1:B3)");
expect(getRangeValuesAsMatrix(model, "A6:A7")).toEqual([["#BAD_EXPR"], ["John"]]);
});

test("FILTER accepts errors in condition arguments", () => {
// prettier-ignore
const grid = {
A1: "Alice", B1: "TRUE", C1: "TRUE",
A2: "Peter", B2: "=KABOUM", C2: "TRUE",
A3: "John", B3: "TRUE", C3: "=KABOUM",
};
const model = createModelFromGrid(grid);
setCellContent(model, "A6", "=FILTER(A1:A3, B1:B3, C1:C3)");
expect(getRangeValuesAsMatrix(model, "A6:A8")).toEqual([["Alice"], [null], [null]]);
});
});

describe("UNIQUE function", () => {
Expand Down

0 comments on commit 03d7080

Please sign in to comment.