Sha256: d71642e2ad6068ab8d749f6eac648cfe3e4f5f5b15475b83552231adf16f2a9c

Contents?: true

Size: 996 Bytes

Versions: 10

Compression:

Stored size: 996 Bytes

Contents

module Spruz
  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

10 entries across 10 versions & 1 rubygems

Version Path
spruz-0.2.13 lib/spruz/bijection.rb
spruz-0.2.12 lib/spruz/bijection.rb
spruz-0.2.11 lib/spruz/bijection.rb
spruz-0.2.10 lib/spruz/bijection.rb
spruz-0.2.9 lib/spruz/bijection.rb
spruz-0.2.8 lib/spruz/bijection.rb
spruz-0.2.7 lib/spruz/bijection.rb
spruz-0.2.6 lib/spruz/bijection.rb
spruz-0.2.5 lib/spruz/bijection.rb
spruz-0.2.2 lib/spruz/bijection.rb