Skip to content

Commit

Permalink
Fix VLookup behaviour (again)
Browse files Browse the repository at this point in the history
  • Loading branch information
anmcgrath committed Feb 27, 2024
1 parent b59858c commit 6d36ccc
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
14 changes: 7 additions & 7 deletions src/BlazorDatasheet.Formula.Functions/Lookup/VLookupFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,20 @@ public CellValue Call(CellValue[] args, FunctionCallMetaData metaData)
for (int row = 0; row < nRows; row++)
{
if (dataArr[row][0].IsEqualTo(lookupValue))
{
return dataArr[row][column];
}
else
{
Console.WriteLine($"{dataArr[row][0]} not equal to {lookupValue}");
}
}

return CellValue.Error(ErrorType.Na);
}

var arrAsList = dataArr.Select(x => x[0]).ToList()!;
var indexSearched = arrAsList.BinarySearchClosest(lookupValue);

var indexSearched = arrAsList.BinarySearchIndexOf(lookupValue);
if (indexSearched >= 0)
return dataArr[indexSearched][column];
else
indexSearched = ~indexSearched - 1;

if (indexSearched < 0 || indexSearched > arrAsList.Count - 1)
return CellValue.Error(ErrorType.Na);

Expand Down
13 changes: 8 additions & 5 deletions test/BlazorDatasheet.Test/Functions/LookupFunctionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,19 @@ public void VLookup_With_Range_False_Tests()
//lookup column 2
Eval("=VLOOKUP(4,{1,3;4,5},2,false)").Should().Be(5);
}

[Test]
public void VLookup_With_Range_True_Tests()
{
_env.RegisterFunction("VLOOKUP", new VLookupFunction());
Eval("=VLOOKUP(3,{1;2;4},1)").Should().Be(4);
Eval("=VLOOKUP(0,{1;2;4},1,true)").Should().Be(1);
Eval("=VLOOKUP(3,{1;2;4},1)").Should().Be(2);
Eval("=VLOOKUP(5,{1;2;4},1,true)").Should().Be(4);
// a lookup value outside of the array should be false
Eval("=VLOOKUP(5,{1;3;4},1,true)").Should().BeOfType<FormulaError>();
Eval("=VLOOKUP(0,{1;3;4},1,true)").Should().BeOfType<FormulaError>();
//lookup column 2
Eval("=VLOOKUP(3,{1,3;4,5},2,true)").Should().Be(5);
// data:
// 1 3
// 4 5
Eval("=VLOOKUP(4,{1,3;4,5},2,true)").Should().Be(5);
}
}

0 comments on commit 6d36ccc

Please sign in to comment.