Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class IndexedArray
- include Enumerable
- def initialize
- @hash = {}
- @open = []
- @last = 0
- end
- def << (value)
- id = @open.empty? ? @hash.size : @open.shift
- @hash[id] = value
- @last = id
- end
- def delete(id)
- @hash.delete(id)
- @open << id
- if @hash.empty?
- @open.clear
- else
- max_index = @hash.keys.max
- @open.select! { |i| i <= max_index }
- @open.sort!
- end
- end
- def [](id)
- @hash[id]
- end
- def each
- return enum_for(:each) unless block_given?
- @hash.keys.each do |id|
- yield @hash[id] if @hash.key?(id)
- end
- end
- def each_with_index
- @hash.keys.each do |id|
- yield @hash[id], id if @hash.key?(id)
- end
- end
- def include?(id)
- @hash.key?(id)
- end
- def index(value)
- @hash.key(value)
- end
- def each_index
- @hash.keys.each do |id|
- yield id if @hash.key?(id)
- end
- end
- def clear
- @hash.clear
- @open.clear
- end
- def size
- @hash.size
- end
- def last
- @hash[@last]
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement