B4J Tutorial [BANano] [SOLVED] What is the right way to pass arrays to functions?

Mashiane

Expert
Licensed User
Ola

My code is returning NAN, however if I hard code the array elements it works and returns 1. What am I doing wrong?

B4X:
'find the min of the list elements
Sub min1(args As List) As Double
    'this does not work
    Dim rslt As Double = math.GetFunction("min").Execute(args).Result
    'this works
    'Dim rslt As Double = math.GetFunction("min").Execute(Array As Int(1,2,3,4,5)).Result
    Return rslt
End Sub
Usage:

B4X:
Sub Init
    'initialize the math object
    math.Initialize("Math")
    '
    Dim res As Double = min1(Array As Int(1, 2, 3, 4, 5))
    banano.Alert(res)
End Sub
Source code attached, can I get help please.

Thanks.
 

Attachments

alwaysbusy

Expert
Licensed User
This is because the Math.min function does expect the contents of an array, not an array itself. In Javascript ES6, one would use the spread operator (... three dots) to do that, but there is no equivalent for that in B4J.

So we would need the IDE of B4J to be able to accept code like this (which it does not of course):
B4X:
' var rslt = Math.min(...args);
Dim rslt As Double = math.GetFunction("min").Execute(...args).Result
' or shorter
Dim rslt As Double = math.RunMethod("min",...args).Result
The fix is using the ES2015 version of the spread operator using the JavaScript apply method:
B4X:
' var rslt = Math.min.apply(Math, args); ' the ES2015 apply method
Dim rslt As Double = math.GetFunction("min").GetFunction("apply").Execute(Array(math,args)).Result
' or shorter
Dim rslt As Double = math.GetFunction("min").RunMethod("apply", Array(math,args)).Result
Alwaysbusy
 
Top