1

I think the question is pretty self explanatory. How to break out of a loop in map, filter and other such operators that loop? (or at least a workaround to achieve this)

Thanks

vikram92
  • 94
  • 9

1 Answers1

3

You're not going to be able to do it with any built-in functions like map, filter and reduce, so this leaves you with recursion. To emulate a break, your base case will need to check the array for length, as well as for the break condition. Here's an example that takes in an array and returns an array containing each value until an even number is reached:

%dw 1.0
output application/json

%function breakCondition(n)
  mod(n, 2) == 0

%function untilEven(arr, out=[])
  out when (isEmpty(arr) or breakCondition(arr[0]))
    otherwise untilEven(arr[1 to -1], arr[0])
---
untilEven([3, 5, 1, 6, 7, 9])

Returns:

[3, 5, 1]

For future reference, here is the same example in 2.0:

%dw 2.0
output application/json

fun breakCondition(n) =
  mod(n, 2) == 0

fun untilEven(arr, out=[]) =
  if (isEmpty(arr) or breakCondition(arr[0]))
    out
  else 
    untilEven(arr[1 to -1], arr[0])
---
untilEven([3, 5, 1, 6, 7, 9])
jerney
  • 2,187
  • 1
  • 19
  • 31