Skip to content

Commit

Permalink
Ensure only non-root nodes are marked as terminal
Browse files Browse the repository at this point in the history
  • Loading branch information
gonzedge committed Feb 20, 2024
1 parent 20d45ba commit 9b59924
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/rambling/trie/nodes/raw.rb
Expand Up @@ -11,7 +11,7 @@ class Raw < Rambling::Trie::Nodes::Node
# @note This method clears the contents of the chars variable.
def add chars
if chars.empty?
terminal!
terminal! unless root?
else
add_to_children_tree chars
end
Expand Down
6 changes: 6 additions & 0 deletions spec/lib/rambling/trie/container_spec.rb
Expand Up @@ -34,6 +34,12 @@
expect(root.children.size).to eq 1
expect(root.to_a).to eq %w(hello)
end

it 'does nothing with empty strings' do
add_word container, ''
expect(root.children.size).to eq 0
expect(root.to_a).to be_empty
end
# rubocop:enable RSpec/MultipleExpectations
end

Expand Down
16 changes: 16 additions & 0 deletions spec/lib/rambling/trie/nodes/raw_spec.rb
Expand Up @@ -32,6 +32,22 @@ def assign_letter letter
end

describe '#add' do
context 'when the node has no parent' do
before { node.parent = nil }

context 'when adding an empty string' do
before { add_word node, '' }

it 'does not add new children' do
expect(node.children.size).to eq 0
end

it 'does not mark itself as terminal' do
expect(node).not_to be_terminal
end
end
end

context 'when the node has no branches' do
before { add_word node, 'abc' }

Expand Down
10 changes: 9 additions & 1 deletion spec/lib/rambling/trie/stringifyable_spec.rb
Expand Up @@ -4,14 +4,22 @@

describe Rambling::Trie::Stringifyable do
describe '#as_word' do
let(:node) { Rambling::Trie::Nodes::Raw.new }
let(:parent) { Rambling::Trie::Nodes::Raw.new }
let(:node) { Rambling::Trie::Nodes::Raw.new nil, parent }

context 'with an empty node' do
before { add_word node, '' }

it 'returns nil' do
expect(node.as_word).to be_empty
end

context 'with no parent' do
let(:parent) { nil }
it 'returns nil' do
expect(node.as_word).to be_empty
end
end
end

context 'with one letter' do
Expand Down

0 comments on commit 9b59924

Please sign in to comment.