Trying to compare 2 lists with map

I have 2 list with map

products= [
  %{
    "id" => "7",
    "use_count" => 1,
    "name" => "A",
    "price" => "$1",
    "base_count" => 2
  },
  %{
    "id" => "8",
    "use_count" => 0,
    "name" => "B",
    "price" => "$14",
    "base_count" => 0
  },
  %{
    "id" => "9",
    "use_count" => 1,
    "name" => "C",
    "price" => "$29",
    "base_count" => 0
  }
]

and

margin=[
  %{name: "aa", id: 9, base_count: 1},
  %{name: "bb", id: 7, base_count: 1}
]

I want to compare 2 list based on id . If for any base_count in products is less than base_count of margin , then I want throw the error as

        {:error, "product count cant be less than margin count"}

Can anyone please help?

Thanks in advance.

The first step you want to do is probably converting (or create as such) your margin into a more efficient data structure like a map from id to base_count:

margin = margin |> Enum.map(&{&1[:id], &1[:base_count]}) |> Map.new()

Then you can use Enum.all? to check if all items in another list fullfil a given condition.

Enum.all?(products, fn p ->
  p["base_count"] >= margin[p["id"]]
end)

PS: I have not covered the case that there are items in products which do not have their constrraints in margin, you need to add that on your own.

3 Likes