Advertisement
LeonMMS

IndexedArray

Jun 16th, 2025 (edited)
1,124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.07 KB | None | 0 0
  1. class IndexedArray
  2.   include Enumerable
  3.   def initialize
  4.     @hash = {}
  5.     @open = []
  6.     @last = 0
  7.   end
  8.  
  9.   def << (value)
  10.     id =  @open.empty? ? @hash.size : @open.shift
  11.     @hash[id] = value
  12.     @last = id
  13.   end
  14.  
  15.   def delete(id)
  16.     @hash.delete(id)
  17.     @open << id
  18.     if @hash.empty?
  19.       @open.clear
  20.     else
  21.       max_index = @hash.keys.max
  22.       @open.select! { |i| i <= max_index }
  23.       @open.sort!
  24.     end
  25.   end
  26.  
  27.   def [](id)
  28.     @hash[id]
  29.   end
  30.  
  31.   def each
  32.     return enum_for(:each) unless block_given?
  33.     @hash.keys.each do |id|
  34.       yield @hash[id] if @hash.key?(id)
  35.     end
  36.   end
  37.  
  38.   def each_with_index
  39.     @hash.keys.each do |id|
  40.       yield @hash[id], id if @hash.key?(id)
  41.     end
  42.   end
  43.  
  44.   def include?(id)
  45.     @hash.key?(id)
  46.   end
  47.  
  48.   def index(value)
  49.     @hash.key(value)
  50.   end
  51.  
  52.   def each_index
  53.     @hash.keys.each do |id|
  54.       yield id if @hash.key?(id)
  55.     end
  56.   end
  57.  
  58.   def clear
  59.     @hash.clear
  60.     @open.clear
  61.   end
  62.  
  63.   def size
  64.     @hash.size
  65.   end
  66.  
  67.   def last
  68.     @hash[@last]
  69.   end
  70.  
  71. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement