Skip to content

Commit 43ae8d0

Browse files
Add std.maxArray in standard library (#1081)
Co-authored-by: Dave Cunningham <[email protected]>
1 parent b42d8ec commit 43ae8d0

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

doc/_stdlib_gen/stdlib-content.jsonnet

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1350,6 +1350,14 @@ local html = import 'html.libsonnet';
13501350
|||
13511351
Return the min of all element in <code>arr</code>.
13521352
},
1353+
{
1354+
name: 'maxArray',
1355+
params: ['arr', 'keyF', 'onEmpty'],
1356+
availableSince: 'upcoming',
1357+
description: html.paragraphs([
1358+
|||
1359+
Return the max of all element in <code>arr</code>.
1360+
},
13531361
{
13541362
name: 'contains',
13551363
params: ['arr', 'elem'],

stdlib/std.jsonnet

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1715,6 +1715,18 @@ limitations under the License.
17151715
a;
17161716
std.foldl(minFn, arr, minVal),
17171717

1718+
maxArray(arr, keyF=id, onEmpty=error 'Expected at least one element in array. Got none')::
1719+
if std.length(arr) == 0 then
1720+
onEmpty
1721+
else
1722+
local maxVal = arr[0];
1723+
local maxFn(a, b) =
1724+
if std.__compare(keyF(a), keyF(b)) < 0 then
1725+
b
1726+
else
1727+
a;
1728+
std.foldl(maxFn, arr, maxVal),
1729+
17181730
xor(x, y):: x != y,
17191731

17201732
xnor(x, y):: x == y,

test_suite/stdlib.jsonnet

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1547,6 +1547,11 @@ std.assertEqual(std.sum([1, 2, 3]), 6) &&
15471547
std.assertEqual(std.minArray([1, 2, 3]), 1) &&
15481548
std.assertEqual(std.minArray(['1', '2', '3']), '1') &&
15491549

1550+
std.assertEqual(std.maxArray([1, 2, 3]), 3) &&
1551+
std.assertEqual(std.maxArray(['1', '2', '3']), '3') &&
1552+
std.assertEqual(std.maxArray(['a', 'x', 'z']), 'z') &&
1553+
1554+
15501555
std.assertEqual(std.xor(true, false), true) &&
15511556
std.assertEqual(std.xor(true, true), false) &&
15521557

0 commit comments

Comments
 (0)