Skip to content

Commit

Permalink
[FIX] functions: XLOOKUP linear search crashes without lookup values
Browse files Browse the repository at this point in the history
How to reproduce:
- In an empty sheet, write `=XLOOKUP("test",F1:F20,G1:G20,,0,-1)`

Task: 4320993
X-original-commit: 183a02d
Part-of: #5239
Signed-off-by: Adrien Minne (adrm) <[email protected]>
Signed-off-by: Rémi Rahir (rar) <[email protected]>
  • Loading branch information
rrahir committed Nov 20, 2024
1 parent d2e1e7f commit b90326b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/functions/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -913,7 +913,9 @@ export function linearSearch<T>(
return reverseSearch ? numberOfValues - i - 1 : i;
}
}
return reverseSearch ? numberOfValues - closestMatchIndex - 1 : closestMatchIndex;
return reverseSearch && closestMatchIndex !== -1
? numberOfValues - closestMatchIndex - 1
: closestMatchIndex;
}

/**
Expand Down
9 changes: 9 additions & 0 deletions tests/functions/module_lookup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1319,6 +1319,15 @@ describe("XLOOKUP formula", () => {
"#,##0[$$]"
);
});

test("Empty lookup range with reverse search mode does not crash", () => {
const grid = evaluateGrid({
A1: "=XLOOKUP(5, B1:B6, C1:C6, , , -1 )",
A2: "=XLOOKUP(5, B1:B6, C1:C6, , , -2 )",
});
expect(grid.A1).toBe("#N/A");
expect(grid.A2).toBe("#N/A");
});
});

describe("INDEX formula", () => {
Expand Down

0 comments on commit b90326b

Please sign in to comment.