Skip to content

Commit

Permalink
std.compactArray recursively flattens multiple arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
bitmaybewise committed May 23, 2023
1 parent 8ea27ab commit 9398f91
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
14 changes: 14 additions & 0 deletions doc/_stdlib_gen/stdlib-content.jsonnet
Expand Up @@ -1349,6 +1349,20 @@ local html = import 'html.libsonnet';
},
],
},
{
name: 'compactArrays',
params: ['arrs'],
availableSince: 'upcoming',
description: |||
Concatenate an array of arrays into a single flattened array, removing null values.
|||,
examples: [
{
input: 'std.compactArrays([[1, 2], [], [3, [4]], [[5, 6, [null]], [7, 8]]])',
output: std.compactArrays([1, 2, 3, 4, 5, 6, 7, 8]),
},
],
},
{
name: 'reverse',
params: ['arrs'],
Expand Down
10 changes: 10 additions & 0 deletions stdlib/std.jsonnet
Expand Up @@ -865,6 +865,16 @@ limitations under the License.
flattenArrays(arrs)::
std.foldl(function(a, b) a + b, arrs, []),

compactArray(arrs)::
local foldable = function(accumulator, value)
if std.isArray(value) then
accumulator + std.compactArray(value)
else if value == null then
accumulator
else
accumulator + [value];
std.foldl(foldable, arrs, []),

manifestIni(ini)::
local body_lines(body) =
std.join([], [
Expand Down
5 changes: 5 additions & 0 deletions test_suite/stdlib.jsonnet
Expand Up @@ -313,6 +313,11 @@ std.assertEqual(std.lines(['a', null, 'b']), 'a\nb\n') &&

std.assertEqual(std.flattenArrays([[1, 2, 3], [4, 5, 6], []]), [1, 2, 3, 4, 5, 6]) &&

std.assertEqual(std.compactArray([]), []) &&
std.assertEqual(std.compactArray([1, 2, 3]), [1, 2, 3]) &&
std.assertEqual(std.compactArray([1, [2, 3]]), [1, 2, 3]) &&
std.assertEqual(std.compactArray([[1], [2, 3], []]), [1, 2, 3]) &&

std.assertEqual(
std.manifestIni({
main: { a: '1', b: '2' },
Expand Down

0 comments on commit 9398f91

Please sign in to comment.