Skip to content

Commit fe3750f

Browse files
authored
feat: implement std.avg (#1087)
* Add std.avg in standard library
1 parent fe8179a commit fe3750f

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

doc/_stdlib_gen/stdlib-content.jsonnet

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1394,6 +1394,16 @@ local html = import 'html.libsonnet';
13941394
|||,
13951395
]),
13961396
},
1397+
{
1398+
name: 'avg',
1399+
params: ['arr'],
1400+
availableSince: '0.20.0',
1401+
description: html.paragraphs([
1402+
|||
1403+
Return average of all element in <code>arr</code>.
1404+
|||,
1405+
]),
1406+
},
13971407
{
13981408
name: 'remove',
13991409
params: ['arr', 'elem'],

stdlib/std.jsonnet

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1709,6 +1709,12 @@ limitations under the License.
17091709

17101710
sum(arr):: std.foldl(function(a, b) a + b, arr, 0),
17111711

1712+
avg(arr)::
1713+
if std.length(arr) == 0 then
1714+
error 'Cannot calculate average of an empty array.'
1715+
else
1716+
std.sum(arr)/std.length(arr),
1717+
17121718
minArray(arr, keyF=id, onEmpty=error 'Expected at least one element in array. Got none')::
17131719
if std.length(arr) == 0 then
17141720
onEmpty

test_suite/stdlib.jsonnet

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1549,6 +1549,10 @@ std.assertEqual(std.all([]), true) &&
15491549

15501550
std.assertEqual(std.sum([1, 2, 3]), 6) &&
15511551

1552+
std.assertEqual(std.avg([1, 2, 3]), 2) &&
1553+
std.assertEqual(std.avg([0, 0, 0]), 0) &&
1554+
std.assertEqual(std.avg([1, 1, 2.5]), 1.5) &&
1555+
15521556
std.assertEqual(std.minArray([1, 2, 3]), 1) &&
15531557
std.assertEqual(std.minArray(['1', '2', '3']), '1') &&
15541558

0 commit comments

Comments
 (0)