Class: TypedMap

Inherits:
Object
  • Object
show all
Defined in:
lib/typed_map.rb,
lib/typed_map/version.rb

Constant Summary collapse

INTERFACE_METHOD_NAMES =
%i[add keys [] has? count length to_a to_h].freeze
VERSION =
"0.1.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ktype:, vtype:) ⇒ TypedMap

Returns a new instance of TypedMap.

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
# File 'lib/typed_map.rb', line 14

def initialize(ktype:, vtype:)
  raise ArgumentError, "'ktype' should be an instance of Class" unless ktype.instance_of?(Class)
  raise ArgumentError, "'vtype' should be an instance of Class" unless vtype.instance_of?(Class)

  @ktype = ktype
  @vtype = vtype

  @map = {}
end

Instance Attribute Details

#ktypeObject (readonly)

Returns the value of attribute ktype.



4
5
6
# File 'lib/typed_map.rb', line 4

def ktype
  @ktype
end

#vtypeObject (readonly)

Returns the value of attribute vtype.



4
5
6
# File 'lib/typed_map.rb', line 4

def vtype
  @vtype
end

Class Method Details

.interface_method_namesObject



9
10
11
# File 'lib/typed_map.rb', line 9

def interface_method_names
  INTERFACE_METHOD_NAMES
end

Instance Method Details

#[](k) ⇒ Object

Raises:

  • (ArgumentError)


36
37
38
39
40
41
# File 'lib/typed_map.rb', line 36

def [](k)
  raise ArgumentError, "'k' should be an instance of #{ktype}" unless k.instance_of?(ktype)
  raise ArgumentError, "key '#{k}' not exists"                 unless has?(k)

  @map[k]
end

#add(k, v) ⇒ Object

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
# File 'lib/typed_map.rb', line 24

def add(k, v)
  raise ArgumentError, "'k' should be an instance of #{ktype}" unless k.instance_of?(ktype)
  raise ArgumentError, "'v' should be an instance of #{vtype}" unless v.instance_of?(vtype)
  raise ArgumentError, "key '#{k}' already exists"             if has?(k)

  @map[k] = v
end

#countObject Also known as: length



49
50
51
# File 'lib/typed_map.rb', line 49

def count
  @map.count
end

#has?(k) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


43
44
45
46
47
# File 'lib/typed_map.rb', line 43

def has?(k)
  raise ArgumentError, "'k' should be an instance of #{ktype}" unless k.instance_of?(ktype)

  @map.has_key? k
end

#keysObject



32
33
34
# File 'lib/typed_map.rb', line 32

def keys
  @map.keys
end

#to_aObject



55
56
57
# File 'lib/typed_map.rb', line 55

def to_a
  @map.to_a
end

#to_hObject



59
60
61
# File 'lib/typed_map.rb', line 59

def to_h
  @map.dup
end