Sha256: e707709a45aff236020457d026e2534097e40d6a5bc63b6db22ebb5494421a6f

Contents?: true

Size: 1.19 KB

Versions: 7

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

module DataStructures101
  # HashTable implementation using separate chaining strategy
  # for collision-resolution
  # It subclasses Hash::BaseHashTable
  # @author Rene Hernandez
  # @since 0.2
  class ChainedHashTable < Hash::BaseHashTable
    def initialize(capacity: 31, prime: 109_345_121, compression_lambda: nil)
      super
    end

    private

    def bucket_find(hash_code, key)
      bucket = @table[hash_code]
      return nil if bucket.nil?

      bucket.find(key)
    end

    def bucket_insert(hash_code, key, value)
      bucket = @table[hash_code]
      bucket = @table[hash_code] = Hash::Bucket.new if bucket.nil?

      old_size = bucket.size
      old_value = bucket.insert(key, value)
      @size += (bucket.size - old_size)

      old_value
    end

    def bucket_delete(hash_code, key)
      bucket = @table[hash_code]
      return nil if bucket.nil?

      old_size = bucket.size
      value = bucket.delete(key)
      @size -= (old_size - bucket.size)

      value
    end

    def bucket_each
      @table.each do |bucket|
        next if bucket.nil?

        bucket.each do |key, value|
          yield(key, value)
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
data_structures_101-0.3.1 lib/data_structures_101/chained_hash_table.rb
data_structures_101-0.3.0 lib/data_structures_101/chained_hash_table.rb
data_structures_101-0.2.10 lib/data_structures_101/chained_hash_table.rb
data_structures_101-0.2.9 lib/data_structures_101/chained_hash_table.rb
data_structures_101-0.2.8 lib/data_structures_101/chained_hash_table.rb
data_structures_101-0.2.7 lib/data_structures_101/chained_hash_table.rb
data_structures_101-0.2.6 lib/data_structures_101/chained_hash_table.rb