0

I am currently trying to iterate over a list of ManagedObjects in event processing through a script. It should check a condition for each ManagedObject in the list and once it is true return that Object.

This is my script:

 create expression ManagedObject getCurrentDepot(position, listObjects) [ 
     for (i = 0; i <= listObjects.length; i++) { 
         var obj = listObjects[i]; 
         var distance = distance(position.lat, position.lng, obj.Geofence.lat, obj.Geofence.lng); 
         if (distance <= obj.radius ) { 
             depot; 
         } 
     } 
     null; 
 ];

I get the following error:

Error in statement mytest:statement_2! : Incorrect syntax near ';' at line 3 column 26

It complains about this line:

var obj = listObjects[i];

How can I correctly iterate over the list?

TyrManuZ
  • 2,039
  • 1
  • 14
  • 23

2 Answers2

1

The best solution would be to not do the looping in the expression but in the event processing itself.

create expression Boolean isInRange(position, element) [
     var distance = distance(position.lat, position.lng, element.Geofence.lat, obj.Geofence.lng); 
     if (distance <= element.radius ) { 
         true; 
     }
     false;
 ];

insert into MyStreamWithDepot
select
    event.listObjects.firstOf(element => isInRange(event.position, element) is true) as currentDepot
from InputEvent event;

You can have a look at the documentation for the "firstOf" method here esper documentation

TyrManuZ
  • 2,039
  • 1
  • 14
  • 23
  • But this is going to take only the first element that satisfy the condition, isn't ? What about if other element also satisfies the condition? – Jorge Nov 28 '18 at 22:20
  • Yes correct firstOf will only return the first match. Maybe check takeWhile() function. It might suit your need. – TyrManuZ Nov 29 '18 at 09:35
  • Taking in consideration the takeWhile() you mention and follow the example you wrote, every time the takeWhile() return a value the MyStreamWithDepot stream is going to be trigger or will be trigger just once with all events that apply to the condition inside the takeWhile()? – Jorge Nov 29 '18 at 16:07
  • Maybe you should move that into an own question as this has nothing to do with the question here. I have never used it but it looks like it returns a collection – TyrManuZ Nov 29 '18 at 16:53
0

Try

var distance;
listObjects.forEach(function(obj) {          
        distance  = distance(position.lat, position.lng, obj.Geofence.lat, obj.Geofence.lng); 
         if (distance <= obj.radius ) { 
             depot; 
         } 
     });