Sha256: 560934f562096a3dde1eb7f0bfe205dfc30d8395e51bff9ca90719e5b70280e2

Contents?: true

Size: 1.9 KB

Versions: 10

Compression:

Stored size: 1.9 KB

Contents

module EDTF

  # TODO use bitmasks instead of arrays

  class Uncertainty < Struct.new(:year, :month, :day)

    attr_reader :hash_base
    
    def initialize(year = nil, month = nil, day = nil, hash_base = 1)
      @hash_base = hash_base
      super(year, month, day)
    end
    
    def hash_base=(base)
      @hash_map = false
      @hash_base = base
    end
    
    def uncertain?(parts = members)
      [*parts].any? { |p| !!send(p) }
    end

    def uncertain!(parts = members)
      [*parts].each { |p| send("#{p}=", true) }
      self
    end

    def certain?(parts = members); !uncertain?(parts); end

    def certain!(parts = members)
      [*parts].each { |p| send("#{p}=", false) }
      self
    end
    
    def eql?(other)
      hash == other.hash
    end
    
    def hash
      values.zip(hash_map).reduce(0) { |s, (v, h)|  s + (v ? h : 0) }
    end
    
    private 
    
    def hash_map
      @hash_map ||= (0...length).map { |i| hash_base << i }
    end
    
  end


  class Unspecified < Struct.new(:year, :month, :day)

    U = 'u'.freeze

    def initialize
      super Array.new(4),Array.new(2), Array.new(2)
    end

    def unspecified?(parts = members)
      [*parts].any? { |p| send(p).any? { |u| !!u } }
    end

    def unspecified!(parts = members)
      [*parts].each { |p| send(p).map! { true } }
      self
    end

    def specified?(parts = members); !unspecified?(parts); end

    def specified!(parts = members)
      [*parts].each { |p| send(p).map! { false } }
      self
    end

    alias specific? specified?
    alias unspecific? unspecified?

    alias specific! specified!
    alias unspecific! unspecified!

    private :year=, :month=, :day=

    def to_s
      mask(%w{ ssss ss ss }).join('-')
    end

    def mask(values)
      values.zip(members.take(values.length)).map do |value, mask|
        value.split(//).zip(send(mask)).map { |v,m| m ? U : v }.join
      end
    end
  end

end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
edtf-3.0.0 lib/edtf/uncertainty.rb
edtf-2.3.1 lib/edtf/uncertainty.rb
edtf-2.3.0 lib/edtf/uncertainty.rb
edtf-2.2.0 lib/edtf/uncertainty.rb
edtf-2.1.0 lib/edtf/uncertainty.rb
edtf-2.0.0 lib/edtf/uncertainty.rb
edtf-1.0.0 lib/edtf/uncertainty.rb
edtf-0.0.9 lib/edtf/uncertainty.rb
edtf-0.0.8 lib/edtf/uncertainty.rb
edtf-0.0.7 lib/edtf/uncertainty.rb