Custom Function Flux Query

I’m trying to improve some of my queries by doing some custom functions that perform several calculations. The function I’m trying to simplify is the next one:

``````|> map(fn: (r) => {

garbi = if (r["GARBI"] - r["PV GARBI"] * 0.123) < 0.0 then 0.0 else (r["GARBI"] - r["PV GARBI"] * 0.123)
gregal = if (r["LLEVANT"] - r["PV GARBI"] * 0.317) < 0.0 then 0.0 else (r["GREGAL"] - r["PV GARBI"] * 0.317)
llevant = if (r["GREGAL"] - r["PV GARBI"] * 0.123) < 0.0 then 0.0 else (r["LLEVANT"] - r["PV GARBI"] * 0.123)
mestral = if (r["MESTRAL"] - r["PV GARBI"] * 0.063) < 0.0 then 0.0 else (r["MESTRAL"] - r["PV GARBI"] * 0.063)
montseny = if (r["MONTSENY"] - r["PV GARBI"] * 0.079) < 0.0 then 0.0 else (r["MONTSENY"] - r["PV GARBI"] * 0.079)
pedraforca = if (r["PEDRAFORCA"] - r["PV GARBI"] * 0.071) < 0.0 then 0.0 else (r["PEDRAFORCA"] - r["PV GARBI"] * 0.071)
puigmal = if (r["PUIGMAL"] - r["PV GARBI"] * 0.043) < 0.0 then 0.0 else (r["PUIGMAL"] - r["PV GARBI"] * 0.043)
suport = if (r["SUPORT"] - r["PV GARBI"] * 0.089) < 0.0 then 0.0 else (r["SUPORT"] - r["PV GARBI"] * 0.089)
tramuntana = if (r["TRAMUNTANA"] - r["PV GARBI"] * 0.019) < 0.0 then 0.0 else (r["TRAMUNTANA"] - r["PV GARBI"] * 0.019)
xaloc = if (r["XALOC"] - r["PV GARBI"] * 0.073) < 0.0 then 0.0 else (r["XALOC"] - r["PV GARBI"] * 0.073)

total = garbi + gregal + llevant + mestral + montseny + pedraforca + puigmal + suport + tramuntana + xaloc

return {
_value: gregal,
_total: total,
_time: r._time
}
})
``````

What I’m trying to accomplish is simplifying the code by using an expression like:

``````|> map(fn: (r) => {

balances = doBalances(buildings: buildings, coeff: coeff, r:r)

return {
_value: balances.building,
_total: balances.total,
_time: r._time
}
})
``````

where doBalances is defined as

``````buildings = ["GARBI",..."XALOC"]
coeff = [0.123, ... ,0.073]

doBalances = (buildings, coeff, r) =>  {

result = {}

buildings
|> array.map(fn: (x) => {

//Do operation
balance = 12 //Operation should be described here, and key for the record should be the building name

result = {result with balance: balance}

return {}
})

return result
}
}
``````

What I’m trying to avoid is to do a generic function to write the query and to generalise this procedure on the same FLUX query. Buildings array will be different in each particular case so I want to do it more generic. If what I’m trying to accomplish is not possible with current FLUX functionalities I’ll do it all with javascript function on my code.

If my explanation is not clear I can give more details.