Sha256: 97f665fd788e131420faa5e42452e7ad074595c4f601f69ea9f0b82453b08791

Contents?: true

Size: 995 Bytes

Versions: 176

Compression:

Stored size: 995 Bytes

Contents

module Tins
  class Bijection < Hash
    def self.[](*pairs)
      pairs.size % 2 == 0 or
        raise ArgumentError, "odd number of arguments for #{self}"
      new.fill do |obj|
        (pairs.size / 2).times do |i|
          j = 2 * i
          key = pairs[j]
          value = pairs[j + 1]
          obj.key?(key) and raise ArgumentError, "duplicate key #{key.inspect} for #{self}"
          obj.inverted.key?(value) and raise ArgumentError, "duplicate value #{value.inspect} for #{self}"
          obj[pairs[j]] = pairs[j + 1]
        end
      end
    end

    def initialize(inverted = Bijection.new(self))
      @inverted = inverted
    end

    def fill
      if empty?
        yield self
        freeze
      end
      self
    end

    def freeze
      r = super
      unless @inverted.frozen?
        @inverted.freeze
      end
      r
    end

    def []=(key, value)
      key?(key) and return
      super
      @inverted[value] = key
    end

    attr_reader :inverted
  end
end

Version data entries

176 entries across 158 versions & 9 rubygems

Version Path
tdiary-5.1.2 vendor/bundle/ruby/2.6.0/gems/tins-0.13.2/lib/tins/bijection.rb
tins-1.25.0 lib/tins/bijection.rb
tdiary-5.1.1 vendor/bundle/ruby/2.6.0/gems/tins-0.13.2/lib/tins/bijection.rb
tdiary-5.1.1 vendor/bundle/ruby/2.7.0/gems/tins-1.24.1/lib/tins/bijection.rb
tins-1.24.1 lib/tins/bijection.rb
tins-1.24.0 lib/tins/bijection.rb
tins-1.23.0 lib/tins/bijection.rb
tdiary-5.1.0 vendor/bundle/gems/tins-1.22.2/lib/tins/bijection.rb
tins-1.22.2 lib/tins/bijection.rb
tins-1.22.1 lib/tins/bijection.rb
tins-1.22.0 lib/tins/bijection.rb
tins-1.21.1 lib/tins/bijection.rb
tins-1.21.0 lib/tins/bijection.rb
tins-1.20.3 lib/tins/bijection.rb
tdiary-5.0.13 vendor/bundle/gems/tins-1.20.2/lib/tins/bijection.rb
tdiary-5.0.12.1 vendor/bundle/gems/tins-1.20.2/lib/tins/bijection.rb
tdiary-5.0.11 vendor/bundle/gems/tins-1.16.3/lib/tins/bijection.rb
tdiary-5.0.11 vendor/bundle/gems/tins-1.20.2/lib/tins/bijection.rb
tins-1.20.2 lib/tins/bijection.rb
tins-1.20.1 lib/tins/bijection.rb