1

I have multiple functions:

fun testadd(payload) = 
({
addition: payload.value1 as Number + payload.value2 as Number
})

fun testsub(payload) = 
({
substraction: payload.value1 as Number - payload.value2 as Number
})

fun testmultiply(payload) = 
({
multiplication: payload.value1 as Number * payload.value2 as Number
})

I want to call the function dynamically based on the value of "Operation" property/element. suppose if "Operation" = "testadd" then call testadd function, if "Operation" = "testsub" then call testsub function

Input :

{
"value1" : 10,
"value2" : 20,
"Operation" : "testadd"
}

2 Answers2

6

An alternative here is to use function overloading and literal types. For example:

%dw 2.0
output json

fun binOp(a, b, op : "add") = a + b
fun binOp(a, b, op : "sub") = a - b
fun binOp(a, b, op : "mul") = a * b
---
binOp(10, 20, "add")

DataWeave will call the correct function based on the value of the op parameter.

afelisatti
  • 2,770
  • 1
  • 13
  • 21
  • Note that this method requires to modify the function signature to add the literal type. – aled Aug 21 '22 at 01:59
4

Since functions in DataWeave are named lambdas you can could just convert them to lambdas, assign them as values of an object and use the keys as the names.

Example:

%dw 2.0
output application/json
var functions={
    testadd: (payload) -> {
        addition: payload.value1 as Number + payload.value2 as Number
    },
    testsub: (payload) -> {
        substraction: payload.value1 as Number - payload.value2 as Number
    }
}
---
functions[payload.Operation](payload)

Output (for the input in the question):

{
  "addition": 30
}

Alternatively you could have the functions as functions and just reference them by name in the object:

%dw 2.0
output application/json

fun testadd(payload) = {
    addition: payload.value1 as Number + payload.value2 as Number
}

fun testsub(payload) = {
    substraction: payload.value1 as Number - payload.value2 as Number
}

var functions={
    testadd: testadd,
    testsub: testsub
}
---
functions[payload.Operation](payload)
aled
  • 21,330
  • 3
  • 27
  • 34