mushu8
List limit number of items
Hi,
is there a preferred way to keep a list number of items under a certain limit ?
In my project there is a GenServer module receiving events and stacking them in a list where only the X last one must be kept for analysis.
Currently I have this implementation :
each time an element is pushed in this list, the size of the list is checked and List.delete_at(list, -1) is called in case the limit has been reached.
It’s simple but I’m feeling it could be improved, specially the part where the size of the list is checked at each new event…
Most Liked
zachallaun
A similar question came up recently; here was my suggestion: Term container supporting `push(term)` and `get_last_100()` - #4 by zachallaun
zachallaun
Yep! Remember that all data structures in Elixir (and Erlang) are immutable, so all you have to do is keep a reference to your original queue.
That said, :queue.get/1 will return just the first element (without modifying the queue).
zachallaun
Whatever works for you!
In case it makes any difference, queues can be split and converted to lists:
def pop_many(q, n) do
{items, q} = :queue.split(n, q)
{:queue.to_list(items), q}
end
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









