Merging Lists

I have two lists:

  1. A list of Ecto structs taken from the database which ranges from 0-10 in length
  2. A list of 10 blank structs I create in my controller

The purpose is to always show 10 forms to create/edit associations.

My code now:

tokens = campaign.tokens ++ List.duplicate(%Token{}, 10) |> Enum.take(10)

Is there a better way of merging these lists so I overwrite the blanks with the fetched structs?

You can use the array API from Erlang, although I am not sure if it is a ā€œbetterā€ way. http://erlang.org/doc/man/array.html#from_list-2

 array = :array.from_list(compaign.tokens, %Token{})
:array.resize(10, array) |> :array.to_list()
2 Likes

For note, even this is likely to be more efficient than the array work above, although you could save ā€˜someā€™ calculations (small though they may be because you only have 10 elements to take) with:

tokens = campaign.tokens ++ List.duplicate(%Token{}, 10 - length(campaign.tokens))

And that is probably the fastest way to do it.

1 Like

Given itā€™s only 10 elements, I donā€™t think there will be any visible performance difference unless you call the function in some very tight loop.

@OvermindDL1ā€™s solution is the most readable for me.

2 Likes

Although if campaign.tokens can be an amount greater than ten, well restrict it in your sql query or check for it or so:

tokens = campaign.tokens ++ List.duplicate(%Token{}, max(0, 10 - length(campaign.tokens)))
1 Like