Skip to content

Commit

Permalink
Concatenate arrays with single elements (sebastienros#547)
Browse files Browse the repository at this point in the history
#Fixes 542
  • Loading branch information
sebastienros authored Dec 20, 2022
1 parent 7cb3357 commit 91dcc86
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
21 changes: 21 additions & 0 deletions Fluid.Tests/ArrayFiltersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,27 @@ public void Concat()
Assert.Equal(6, result.Result.Enumerate(context).Count());
}

[Fact]
public void ConcatSingleValue()
{
var input = new StringValue("a");

var arguments = new FilterArguments().Add(
new ArrayValue(new[] {
new StringValue("1"),
new StringValue("2"),
new StringValue("3")
})
);

var context = new TemplateContext();

var result = ArrayFilters.Concat(input, arguments, context);

Assert.Equal("a", result.Result.Enumerate(context).First().ToStringValue());
Assert.Equal(4, result.Result.Enumerate(context).Count());
}

[Fact]
public async Task Map()
{
Expand Down
31 changes: 21 additions & 10 deletions Fluid/Filters/ArrayFilters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,26 +49,37 @@ public static ValueTask<FluidValue> Last(FluidValue input, FilterArguments argum

public static ValueTask<FluidValue> Concat(FluidValue input, FilterArguments arguments, TemplateContext context)
{
if (input.Type != FluidValues.Array)
{
return input;
}
var arg = arguments.At(0);

if (arguments.At(0).Type != FluidValues.Array)
if (input.Type != FluidValues.Array && arg.Type != FluidValues.Array)
{
return input;
}

var concat = new List<FluidValue>();

foreach(var item in input.Enumerate(context))
if (input.Type == FluidValues.Array)
{
foreach (var item in input.Enumerate(context))
{
concat.Add(item);
}
}
else
{
concat.Add(item);
concat.Add(input);
}

foreach (var item in arguments.At(0).Enumerate(context))
if (arg.Type == FluidValues.Array)
{
foreach (var item in arg.Enumerate(context))
{
concat.Add(item);
}
}
else
{
concat.Add(item);
concat.Add(arg);
}

return new ArrayValue(concat);
Expand Down

0 comments on commit 91dcc86

Please sign in to comment.