From 488f15207b629919056781b5646d08e46e658684 Mon Sep 17 00:00:00 2001 From: Deep Goel Date: Fri, 5 May 2023 14:02:34 +0530 Subject: [PATCH] Add std.maxArray in standard library --- doc/_stdlib_gen/stdlib-content.jsonnet | 8 ++++++++ stdlib/std.jsonnet | 12 ++++++++++++ test_suite/stdlib.jsonnet | 9 +++++++-- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/doc/_stdlib_gen/stdlib-content.jsonnet b/doc/_stdlib_gen/stdlib-content.jsonnet index 40de10df5..39231f848 100644 --- a/doc/_stdlib_gen/stdlib-content.jsonnet +++ b/doc/_stdlib_gen/stdlib-content.jsonnet @@ -1429,6 +1429,14 @@ local html = import 'html.libsonnet'; ||| Return the min of all element in arr. }, + { + name: 'maxArray', + params: ['arr', 'keyF', 'onEmpty'], + availableSince: 'upcoming', + description: html.paragraphs([ + ||| + Return the max of all element in arr. + }, { name: 'contains', params: ['arr', 'elem'], diff --git a/stdlib/std.jsonnet b/stdlib/std.jsonnet index 160dd7eb3..479c84371 100644 --- a/stdlib/std.jsonnet +++ b/stdlib/std.jsonnet @@ -1715,6 +1715,18 @@ limitations under the License. a; std.foldl(minFn, arr, minVal), + maxArray(arr, keyF=id, onEmpty=error 'Expected at least one element in array. Got none'):: + if std.length(arr) == 0 then + onEmpty + else + local maxVal = arr[0]; + local maxFn(a, b) = + if std.__compare(keyF(a), keyF(b)) < 0 then + b + else + a; + std.foldl(maxFn, arr, maxVal), + xor(x, y):: x != y, xnor(x, y):: x == y, diff --git a/test_suite/stdlib.jsonnet b/test_suite/stdlib.jsonnet index 186399245..28cad43ce 100644 --- a/test_suite/stdlib.jsonnet +++ b/test_suite/stdlib.jsonnet @@ -1547,6 +1547,11 @@ std.assertEqual(std.sum([1, 2, 3]), 6) && std.assertEqual(std.minArray([1, 2, 3]), 1) && std.assertEqual(std.minArray(['1', '2', '3']), '1') && +std.assertEqual(std.maxArray([1, 2, 3]), 3) && +std.assertEqual(std.maxArray(['1', '2', '3']), '3') && +std.assertEqual(std.maxArray(['a', 'x', 'z']), 'z') && + + std.assertEqual(std.xor(true, false), true) && std.assertEqual(std.xor(true, true), false) && @@ -1559,7 +1564,7 @@ std.assertEqual(std.round(1.5), 2) && std.assertEqual(std.isEmpty(''), true) && std.assertEqual(std.isEmpty('non-empty string'), false) && -std.contains(std.contains([1, 2, 3], 2), true) && -std.contains(std.contains([1, 2, 3], "foo"), false) && +std.assertEqual(std.contains([1, 2, 3], 2), true) && +std.assertEqual(std.contains([1, 2, 3], 'foo'), false) && true