From 17a5fde6aa1f71c999cb1c2e2b58a40720f59d31 Mon Sep 17 00:00:00 2001 From: Honza Dvorsky Date: Sun, 6 Sep 2015 02:22:44 +0100 Subject: [PATCH] fixed Trie search for single-character queries --- hit.podspec | 2 +- hit/Trie.swift | 7 ++++--- hitTests/TrieTests.swift | 21 ++++++++++++++++++--- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/hit.podspec b/hit.podspec index c0f89a7..c041496 100644 --- a/hit.podspec +++ b/hit.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |s| s.name = "hit" - s.version = "0.2" + s.version = "0.3" s.summary = "Lightweight full-text search written in Swift" s.description = <<-DESC diff --git a/hit/Trie.swift b/hit/Trie.swift index 08687da..8ee116b 100644 --- a/hit/Trie.swift +++ b/hit/Trie.swift @@ -53,14 +53,15 @@ public struct Trie { let prefixHeadRange = TokenRange(start: prefix.startIndex, end: prefix.startIndex.advancedBy(1)) let prefixHead = prefix.substringWithRange(prefixHeadRange) - - if length == 1 { + let emptyTrie = trie.token.characters.count == 0 + + if length == 1 && !emptyTrie { + //potentially might be found if trie matches let match = (trie.token == prefixHead) return match ? trie : nil } - let emptyTrie = trie.token.characters.count == 0 let tokenMatches = trie.token == prefixHead if emptyTrie || tokenMatches { diff --git a/hitTests/TrieTests.swift b/hitTests/TrieTests.swift index 0c8a1e6..bbf40bc 100644 --- a/hitTests/TrieTests.swift +++ b/hitTests/TrieTests.swift @@ -11,10 +11,14 @@ import XCTest @testable import hit class TrieTests: HitTestCase { - + + func commonWords() -> [String] { + let strings = ["swiftkey", "swype", "hello", "london", "reality", "fantasy", "stuff"] + return strings + } + func testTrieCreation_exactMatches() { - - let strings = ["swiftkey", "swype", "hello", "london", "reality", "fantasy"] + let strings = self.commonWords() let trie = Trie(strings: strings) let foundStrings = trie.stringsMatchingPrefix("sw") @@ -54,6 +58,17 @@ class TrieTests: HitTestCase { _ = trie.stringsMatchingPrefix("sw") } } + + func testCorrectness_singleCharSearch() { + let strings = self.commonWords() + let trie = Trie(strings: strings) + + let foundStrings = Set(trie.stringsMatchingPrefix("s")) + XCTAssertEqual(foundStrings.count, 3) + XCTAssert(foundStrings.contains("swiftkey")) + XCTAssert(foundStrings.contains("swype")) + XCTAssert(foundStrings.contains("stuff")) + } }