From 91dcc869374e9a6d37ad8f7caa584f20cbcb763a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Ros?= Date: Tue, 20 Dec 2022 15:54:31 -0800 Subject: [PATCH] Concatenate arrays with single elements (#547) #Fixes 542 --- Fluid.Tests/ArrayFiltersTests.cs | 21 +++++++++++++++++++++ Fluid/Filters/ArrayFilters.cs | 31 +++++++++++++++++++++---------- 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/Fluid.Tests/ArrayFiltersTests.cs b/Fluid.Tests/ArrayFiltersTests.cs index 2b5b56f0..a504b581 100644 --- a/Fluid.Tests/ArrayFiltersTests.cs +++ b/Fluid.Tests/ArrayFiltersTests.cs @@ -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() { diff --git a/Fluid/Filters/ArrayFilters.cs b/Fluid/Filters/ArrayFilters.cs index d61628b0..7d08e42c 100644 --- a/Fluid/Filters/ArrayFilters.cs +++ b/Fluid/Filters/ArrayFilters.cs @@ -49,26 +49,37 @@ public static ValueTask Last(FluidValue input, FilterArguments argum public static ValueTask 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(); - 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);