Class: Trees::Trie

Inherits:
Object
  • Object
show all
Includes:
LowType
Defined in:
lib/trie.rb

Defined Under Namespace

Classes: DuplicatePathError, Result

Constant Summary collapse

PARAM_DELIMITERS =
[' ', ':'].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTrie

Returns a new instance of Trie.



18
19
20
# File 'lib/trie.rb', line 18

def initialize
  @root_node = TrieNode.new
end

Instance Attribute Details

#root_nodeObject (readonly)

Returns the value of attribute root_node.



12
13
14
# File 'lib/trie.rb', line 12

def root_node
  @root_node
end

Instance Method Details

#match(tokens:, current_node: @root_node, index: 0, offset: 0, params: {}) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/trie.rb', line 42

def match(tokens:, current_node: @root_node, index: 0, offset: 0, params: {})
  return [] if tokens.empty?

  [
    *match_static(tokens:, current_node:, index:, offset:, params:),
    *match_dynamic(tokens:, current_node:, index:, offset:, params:)
  ]
end

#merge(line:, current_node: @root_node) ⇒ Object

Raises:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/trie.rb', line 22

def merge(line:, current_node: @root_node)
  @current_index = 0
  path = line.path

  while @current_index < path.length
    key = path[@current_index]

    @current_index += 1

    # Sometimes the key is an entire variable name.
    key = capture_param(path:) if key == ':'

    current_node = current_node.upsert_child(key:)
  end

  raise DuplicatePathError, "Path already defined: #{line.path}" if current_node.line

  current_node.line = line
end