From 336ff9574a240dea8fe109161581981796c679b0 Mon Sep 17 00:00:00 2001 From: Deep Goel Date: Sun, 13 Aug 2023 17:10:51 +0530 Subject: [PATCH] Implementing the GroupBy --- doc/_stdlib_gen/stdlib-content.jsonnet | 10 ++++++++++ stdlib/std.jsonnet | 9 +++++++++ test_suite/stdlib.jsonnet | 3 ++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/doc/_stdlib_gen/stdlib-content.jsonnet b/doc/_stdlib_gen/stdlib-content.jsonnet index dd662773d..d10358f44 100644 --- a/doc/_stdlib_gen/stdlib-content.jsonnet +++ b/doc/_stdlib_gen/stdlib-content.jsonnet @@ -1432,6 +1432,16 @@ local html = import 'html.libsonnet'; |||, ]), }, + { + name: 'groupBy', + params: ['arr', 'keyF', 'onEmpty'], + availableSince: 'upcoming', + description: html.paragraphs([ + ||| + Return an object composed of keys generated from the results of running each element of arr through function. + |||, + ]), + }, ], }, { diff --git a/stdlib/std.jsonnet b/stdlib/std.jsonnet index c861a4aec..bf9f7911f 100644 --- a/stdlib/std.jsonnet +++ b/stdlib/std.jsonnet @@ -1741,6 +1741,15 @@ limitations under the License. a; std.foldl(maxFn, arr, maxVal), + groupBy(arr, keyF=id):: + local foldf(o, e, f) = + local k = std.toString(f(e)); + if std.objectHas(o, k) then + c + {[k]: o[k] + [e]} + else + o + {[k]: [e]}; + std.foldl(function(o, e) foldf(o, e, f), arr, {}); + xor(x, y):: x != y, xnor(x, y):: x == y, diff --git a/test_suite/stdlib.jsonnet b/test_suite/stdlib.jsonnet index e3b290e06..d9126c017 100644 --- a/test_suite/stdlib.jsonnet +++ b/test_suite/stdlib.jsonnet @@ -1560,6 +1560,7 @@ 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.groupBy([1, 1.5, 2, 3], std.floor), { '1': [1, 1.5], '2': [2], '3': [3] }) && std.assertEqual(std.xor(true, false), true) && std.assertEqual(std.xor(true, true), false) && @@ -1597,6 +1598,6 @@ std.assertEqual(std.trim('already trimmed string'), 'already trimmed string') && std.assertEqual(std.trim(' string with spaces on both ends '), 'string with spaces on both ends') && std.assertEqual(std.trim('string with newline character at end\n'), 'string with newline character at end') && std.assertEqual(std.trim('string with tabs at end\t\t'), 'string with tabs at end') && -std.assertEqual(std.trim('string with other special whitespaces at end\f\r\u0085\u00A0'), 'string with carriage return at end') && +std.assertEqual(std.trim('string with other special whitespaces at end\f\r\u0085 '), 'string with carriage return at end') && true