module Dbd::Helpers::OrderedSetCollection
Transforms the mixing class into an OrderedSet.
On the mixing class, enumerable functions are possible, looping over the set in O(n), but it is not intended that the mixing class allows arbitrary access into the collection.
The add_and_return_index module method allows to get an index to an added element, so indexes can be built to access elements in O(1). The mixing class should not expose this index to the added element in it's public API. The goal is to allow other implementations (e.g. with Hadoop, Neo4j, …) with the same API.
Public Class Methods
Adds an element at the end of the collection and returns the array index of that element.
This is not an instance method to avoid it ending up in the public API of classes that mixin this module.
The implementation to find the index of the inserted element with `rindex` is primitive, but I did not see a better way in Ruby to do this (using `size` would certainly be not thread safe, maybe the current approach is thread safe, but that is not tested). @return [Integer] index
# File lib/dbd/helpers/ordered_set_collection.rb, line 79 def self.add_and_return_index(element, collection) collection << element collection.rindex(element) end
Creates @internal_collection in the mixing class.
# File lib/dbd/helpers/ordered_set_collection.rb, line 25 def initialize @internal_collection = [] super end
Public Instance Methods
Inserts an element at the end of the collection. Returns self to allow chaining. @param [Object] element @return [Object] self
# File lib/dbd/helpers/ordered_set_collection.rb, line 35 def <<(element) @internal_collection << element self end
For the Enumerable functionality.
# File lib/dbd/helpers/ordered_set_collection.rb, line 42 def each @internal_collection.each do |e| yield e end end
# File lib/dbd/helpers/ordered_set_collection.rb, line 84 def freeze @internal_collection.freeze self end
This is required as an efficient way to find the last element without stepping through the entire collection. This implementation is probably not thread safe. @return [Object] the last element
# File lib/dbd/helpers/ordered_set_collection.rb, line 53 def last @internal_collection.last end
This is required as an efficient way to find the size without stepping through the entire collection. This implementation is probably not thread safe. @return [Object] the last element
# File lib/dbd/helpers/ordered_set_collection.rb, line 62 def size @internal_collection.size end