From b99ed354bc2e2a91fc4b447bf73d586ce9895429 Mon Sep 17 00:00:00 2001 From: Tomas Strba Date: Fri, 6 Dec 2024 10:12:59 +0100 Subject: [PATCH] Finding URL variants refactored --- DuckDuckGo/Bookmarks/Model/BookmarkList.swift | 17 ++++++++++++++++- .../Bookmarks/Model/BookmarkManager.swift | 10 ++++++---- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/DuckDuckGo/Bookmarks/Model/BookmarkList.swift b/DuckDuckGo/Bookmarks/Model/BookmarkList.swift index 61edd92a17..de5473a1c8 100644 --- a/DuckDuckGo/Bookmarks/Model/BookmarkList.swift +++ b/DuckDuckGo/Bookmarks/Model/BookmarkList.swift @@ -44,7 +44,14 @@ struct BookmarkList { private(set) var allBookmarkURLsOrdered: [IdentifiableBookmark] private var favoriteBookmarksOrdered: [IdentifiableBookmark] - private var itemsDict: [String: [Bookmark]] + private var itemsDict: [String: [Bookmark]] { + didSet { + updateLowercasedItemsDict() + } + } + + // Copy of itemsDict used for efficient lookups of variant URLs + private(set) var lowercasedItemsDict: [String: [Bookmark]] = [:] var totalBookmarks: Int { return allBookmarkURLsOrdered.count @@ -76,6 +83,7 @@ struct BookmarkList { self.allBookmarkURLsOrdered = keysOrdered self.itemsDict = itemsDict self.topLevelEntities = topLevelEntities + updateLowercasedItemsDict() } mutating func insert(_ bookmark: Bookmark) { @@ -149,6 +157,13 @@ struct BookmarkList { return allBookmarkURLsOrdered } + private mutating func updateLowercasedItemsDict() { + lowercasedItemsDict = itemsDict.reduce(into: [:]) { result, entry in + let lowercasedKey = entry.key.lowercased() + result[lowercasedKey] = entry.value + } + } + } private extension BookmarkList { diff --git a/DuckDuckGo/Bookmarks/Model/BookmarkManager.swift b/DuckDuckGo/Bookmarks/Model/BookmarkManager.swift index 9f3c0bb715..e451829b0b 100644 --- a/DuckDuckGo/Bookmarks/Model/BookmarkManager.swift +++ b/DuckDuckGo/Bookmarks/Model/BookmarkManager.swift @@ -182,14 +182,16 @@ final class LocalBookmarkManager: BookmarkManager { /// Finds a bookmark by checking all possible URL variants (http/https, trailing slash). private func findBookmark(forVariantUrl url: URL) -> Bookmark? { - let urlVariants = url.bookmarkButtonUrlVariants() + guard let list = list else { + return nil + } - for variant in urlVariants { - if let bookmark = getBookmark(for: variant) { + for variant in url.bookmarkButtonUrlVariants() { + let variantString = variant.absoluteString + if let bookmark = list.lowercasedItemsDict[variantString]?.first { return bookmark } } - return nil }