Multiply elements within a list in Enum.member?/2

Hello :slight_smile:

We all know what Enum.member?/2 does. In a HEEX we can fast search if a variable contains in a given list

<%= value: Enum.member?(@users, user.id) %>

There a plenty of question about “searching” in more than one list. However, I am looking for something else. I know that Enum.member is /2, but I want to check if elementS exists within the enumerable. With an example:

Enum.member?(["struct of a room"]), user1_id, user2_id, time_id, table_id)

(if the given users are in a same “table” with same “time” → true, if not → false)

My guess is that Enum.member? won’t do the job, however it must be something else. I’m looking at the docs Enum — Elixir v1.13.2, but so far - no luck:)

What are your thoughts?

Best Regards

Take a look at Enum.find/3 or Enum.filter/2.

1 Like

It would be easy to help - if you define struct of room with some sample data.

In addition @bartblast answer - if you are looking to know if something exists you can use Enum.any?

Sample struct of my room:

  %MyApp.Rooms.Room{
    user1_id: 3,
    user2_id: 1,
    table_id: 2,
    time_id: 1,
    # other stuff
  }

Enum.any? returns true if at least one element is in the list. I will demonstrate my goal with an example. Let’s say that we have @user1_id assigned to the socket - 3, and @time_id: 1, @table_id:1

<%= for user1 <- @users1 do %>
  # i want to check here if there is a `Room` with user1.id, user2_id, table_id and time_id. If I was searching only for user1 - e.g if user1.id contains in the list of Rooms I would do it with Enum.member?(@rooms, user1.id). 

<% end %>

\

Its better to do this processing in a function inside Controller and not in heex template. In heex template - render only a collection which is already filtered (in a controller assuming you are using phoenix view)

# this will find if a room exists in rooms with matching table and time and user as user1 or user2
Enum.any?(@rooms, fn r -> 
  r.table_id == @table_id and r.time_id == @time_id and 
  (r.user1_id == @user1_id or r.user2_id == @user1_id)
end)

Enum.find(@rooms, fn r -> 
  r.table_id == @table_id and r.time_id == @time_id and 
  (r.user1_id == @user1_id or r.user2_id == @user1_id)
end)

Enum.filter(@rooms, fn r -> 
  r.table_id == @table_id and r.time_id == @time_id and 
  (r.user1_id == @user1_id or r.user2_id == @user1_id)
end)

You can play around this anonymous function to refine your logic. This anonymous function can be used for Enum.find or Enum.filter also.

3 Likes