oparego

Foreach loop to check a list for dupes


Literally looking to do the below pseudocode in Rego:

listA = {itemA, itemB, itemC}

listB = "items": 
        {
            "item1": "value1",
            "item2": "value2"
        }

foreach item in listB 
{  
If it is already in listA -> Do Nothing  
else Invoke a method 
}

I am going thru the official docs and playing around in the Rego playground but wanted to ask the community if there is a fast and efficient way to do this.


Solution

  • You can do it like this:

    package rego
    
    import future.keywords.in
    
    listA = {"item1", "item2"}
    
    listB = {
        "item1": "item1_value",
        "item2": "item2_value",
        "item3": "item3_value",
    }
    
    ok := [res | val := listB[key]; res := foo(key, val)]
    
    foo(key, val) = res {
        not (key in listA)
        print(key)
        res := sprintf("printed %v", [key])
    }
    
    

    Output: "ok": ["printed item3"]