Skip to content

Commit

Permalink
Merge pull request #918 from gentlesystems/add-prefix-search-to-trie
Browse files Browse the repository at this point in the history
Modified Trie to add prefix support to boolean contains(), plus unit …
  • Loading branch information
richard-ash authored Aug 29, 2020
2 parents 6de22fc + 901aaea commit aeafa95
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
9 changes: 6 additions & 3 deletions Trie/Trie/Trie/Trie.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,12 @@ extension Trie {

/// Determines whether a word is in the trie.
///
/// - Parameter word: the word to check for
/// - Parameters:
/// - word: the word to check for
/// - matchPrefix: whether the search word should match
/// if it is only a prefix of other nodes in the trie
/// - Returns: true if the word is present, false otherwise.
func contains(word: String) -> Bool {
func contains(word: String, matchPrefix: Bool = false) -> Bool {
guard !word.isEmpty else {
return false
}
Expand All @@ -130,7 +133,7 @@ extension Trie {
}
currentNode = childNode
}
return currentNode.isTerminating
return matchPrefix || currentNode.isTerminating
}

/// Attempts to walk to the last node of a word. The
Expand Down
27 changes: 26 additions & 1 deletion Trie/Trie/TrieTests/TrieTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,8 @@ class TrieTests: XCTestCase {
let trieCopy = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? Trie
XCTAssertEqual(trieCopy?.count, trie.count)
}


/// Tests whether word prefixes are properly found and returned.
func testFindWordsWithPrefix() {
let trie = Trie()
trie.insert(word: "test")
Expand All @@ -190,4 +191,28 @@ class TrieTests: XCTestCase {
let wordsUpperCase = trie.findWordsWithPrefix(prefix: "Te")
XCTAssertEqual(wordsUpperCase.sorted(), ["team", "test"])
}

/// Tests whether word prefixes are properly detected on a boolean contains() check.
func testContainsWordMatchPrefix() {
let trie = Trie()
trie.insert(word: "test")
trie.insert(word: "another")
trie.insert(word: "exam")
let wordsAll = trie.contains(word: "", matchPrefix: true)
XCTAssertEqual(wordsAll, true)
let words = trie.contains(word: "ex", matchPrefix: true)
XCTAssertEqual(words, true)
trie.insert(word: "examination")
let words2 = trie.contains(word: "exam", matchPrefix: true)
XCTAssertEqual(words2, true)
let noWords = trie.contains(word: "tee", matchPrefix: true)
XCTAssertEqual(noWords, false)
let unicodeWord = "😬😎"
trie.insert(word: unicodeWord)
let wordsUnicode = trie.contains(word: "😬", matchPrefix: true)
XCTAssertEqual(wordsUnicode, true)
trie.insert(word: "Team")
let wordsUpperCase = trie.contains(word: "Te", matchPrefix: true)
XCTAssertEqual(wordsUpperCase, true)
}
}

0 comments on commit aeafa95

Please sign in to comment.