@@ -1953,6 +1953,42 @@ func builtinMinArray(i *interpreter, arguments []value) (value, error) {
1953
1953
return minVal , nil
1954
1954
}
1955
1955
1956
+ func builtinMaxArray (i * interpreter , arguments []value ) (value , error ) {
1957
+ arrv := arguments [0 ]
1958
+ keyFv := arguments [1 ]
1959
+
1960
+ arr , err := i .getArray (arrv )
1961
+ if err != nil {
1962
+ return nil , err
1963
+ }
1964
+ keyF , err := i .getFunction (keyFv )
1965
+ if err != nil {
1966
+ return nil , err
1967
+ }
1968
+ num := arr .length ()
1969
+ if num == 0 {
1970
+ return nil , i .Error ("Expected at least one element in array. Got none" )
1971
+ }
1972
+ maxVal , err := keyF .call (i , args (arr .elements [0 ]))
1973
+ if err != nil {
1974
+ return nil , err
1975
+ }
1976
+ for index := 1 ; index < num ; index ++ {
1977
+ current , err := keyF .call (i , args (arr .elements [index ]))
1978
+ if err != nil {
1979
+ return nil , err
1980
+ }
1981
+ cmp , err := valueCmp (i , maxVal , current )
1982
+ if err != nil {
1983
+ return nil , err
1984
+ }
1985
+ if cmp < 0 {
1986
+ maxVal = current
1987
+ }
1988
+ }
1989
+ return maxVal , nil
1990
+ }
1991
+
1956
1992
func builtinNative (i * interpreter , name value ) (value , error ) {
1957
1993
str , err := i .getString (name )
1958
1994
if err != nil {
@@ -2385,6 +2421,7 @@ var funcBuiltins = buildBuiltinMap([]builtin{
2385
2421
& unaryBuiltin {name : "decodeUTF8" , function : builtinDecodeUTF8 , params : ast.Identifiers {"arr" }},
2386
2422
& generalBuiltin {name : "sort" , function : builtinSort , params : []generalBuiltinParameter {{name : "arr" }, {name : "keyF" , defaultValue : functionID }}},
2387
2423
& generalBuiltin {name : "minArray" , function : builtinMinArray , params : []generalBuiltinParameter {{name : "arr" }, {name : "keyF" , defaultValue : functionID }}},
2424
+ & generalBuiltin {name : "maxArray" , function : builtinMaxArray , params : []generalBuiltinParameter {{name : "arr" }, {name : "keyF" , defaultValue : functionID }}},
2388
2425
& unaryBuiltin {name : "native" , function : builtinNative , params : ast.Identifiers {"x" }},
2389
2426
& unaryBuiltin {name : "sum" , function : builtinSum , params : ast.Identifiers {"arr" }},
2390
2427
& binaryBuiltin {name : "contains" , function : builtinContains , params : ast.Identifiers {"arr" , "elem" }},
0 commit comments