I have two lists:
A list of Ecto structs taken from the database which ranges from 0-10 in length
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?
Gazler
November 9, 2017, 9:56am
2
You can use the array API from Erlang, although I am not sure if it is a “better” way. array — OTP 29.0.2 (stdlib 8.0.1)
array = :array.from_list(compaign.tokens, %Token{})
:array.resize(10, array) |> :array.to_list()
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.
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.
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)))