Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two arrays in the Rego Language

violation[{"msg": msg}] {
    required:= ["red", "green", "blue"]
    input := ["orange", "purple"]

    msg := sprintf("")
}

I want to compare each value from the input array in the required array. In other languages, two normal loops will do it. but in the Rego language, they are no loops. Does anybody know how can I do it

like image 912
Xameer Avatar asked Sep 07 '25 09:09

Xameer


2 Answers

See the docs section on iteration for how to iterate over a collection. It is however often more idiomatic to work with sets. Following your example:

violation[{"msg": msg}] {
    required := {"red", "green", "blue"}
    input.colors := {"orange", "purple"}
    
    count(required - input.colors) != 0

    msg := sprintf("input.colors (%v) does not contain all required colors (%v), [input.colors, required]")
}

like image 173
Devoops Avatar answered Sep 10 '25 07:09

Devoops


colorSet and requiredSet variable shows how to convert array to set.

Using == operator we can figure out if all colors are present or not

package play

default allColorPresent = false

allColorPresent  {
   colorSet := {x | x := input.colors[_]} 
   requiredSet := {x | x := input. required[_]}
   colorSet == requiredSet
}
like image 37
Bush Avatar answered Sep 10 '25 06:09

Bush