git.delta.rocks / jrsonnet / refs/commits / 371439fb5fc5

difftreelog

feat add std.avg

Yaroslav Bolyukin2023-06-14parent: #54e5a6e.patch.diff
in: master
Upstream issue: https://github.com/google/jsonnet/pull/1087

3 files changed

modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -1,12 +1,22 @@
+#![allow(non_snake_case)]
+
 use jrsonnet_evaluator::{
 	error::{ErrorKind::RuntimeError, Result},
 	function::{builtin, FuncVal},
 	throw,
 	typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
 	val::{equals, ArrValue, IndexableVal, StrValue},
-	Either, IStr, Val,
+	Either, IStr, Thunk, Val,
 };
 
+pub(crate) fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
+	if let Some(on_empty) = on_empty {
+		on_empty.evaluate()
+	} else {
+		throw!("expected non-empty array")
+	}
+}
+
 #[builtin]
 pub fn builtin_make_array(sz: BoundedI32<0, { i32::MAX }>, func: FuncVal) -> Result<ArrValue> {
 	if *sz == 0 {
@@ -230,3 +240,11 @@
 	}
 	Ok(count)
 }
+
+#[builtin]
+pub fn builtin_avg(arr: Vec<f64>, onEmpty: Option<Thunk<Val>>) -> Result<Val> {
+	if arr.is_empty() {
+		return eval_on_empty(onEmpty);
+	}
+	Ok(Val::Num(arr.iter().sum::<f64>() / (arr.len() as f64)))
+}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
81 ("all", builtin_all::INST),81 ("all", builtin_all::INST),
82 ("member", builtin_member::INST),82 ("member", builtin_member::INST),
83 ("count", builtin_count::INST),83 ("count", builtin_count::INST),
84 ("avg", builtin_avg::INST),
84 // Math85 // Math
85 ("abs", builtin_abs::INST),86 ("abs", builtin_abs::INST),
86 ("sign", builtin_sign::INST),87 ("sign", builtin_sign::INST),
modifiedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -13,6 +13,8 @@
 use jrsonnet_gcmodule::Cc;
 use jrsonnet_parser::BinaryOpType;
 
+use crate::eval_on_empty;
+
 #[derive(Copy, Clone)]
 enum SortKeyType {
 	Number,
@@ -207,13 +209,6 @@
 	}
 }
 
-fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
-	if let Some(on_empty) = on_empty {
-		on_empty.evaluate()
-	} else {
-		throw!("expected non-empty array")
-	}
-}
 
 fn eval_keyf(val: Val, key_f: &Option<FuncVal>) -> Result<Val> {
 	if let Some(key_f) = key_f {