Skip to content

Commit

Permalink
add utility the emphasize case insensitive portions of strings (#810)
Browse files Browse the repository at this point in the history
  • Loading branch information
bolsinga committed Jun 15, 2024
1 parent 969776b commit 86d6b3d
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Sources/Site/Utility/String+EmphasizedMatching.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//
// String+EmphasizedMatching.swift
//
//
// Created by Greg Bolsinga on 6/15/24.
//

import Foundation
import RegexBuilder

extension String {
func emphasized(matching fragment: String) -> String {
let regex = Regex {
Capture {
fragment
}
}
.ignoresCase()

return self.replacing(regex, maxReplacements: 1) {
let (_, m) = $0.output
return "**\(m)**"
}
}
}
32 changes: 32 additions & 0 deletions Tests/SiteTests/EmphasizedMatchingTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//
// EmphasizedMatchingTests.swift
//
//
// Created by Greg Bolsinga on 6/15/24.
//

import XCTest

@testable import Site

final class EmphasizedMatchingTests: XCTestCase {
func testJustOneLetterMatchingWithOneMatch() throws {
XCTAssertEqual("Gre".emphasized(matching: "G"), "**G**re")
XCTAssertEqual("Gre".emphasized(matching: "g"), "**G**re")
}

func testJustOneLetterMatchinWithMultipleMatches() throws {
XCTAssertEqual("Greg".emphasized(matching: "G"), "**G**reg")
XCTAssertEqual("Greg".emphasized(matching: "g"), "**G**reg")
}

func testTwoLettersMatchingWithOneMatch() throws {
XCTAssertEqual("Greg".emphasized(matching: "Gr"), "**Gr**eg")
XCTAssertEqual("Greg".emphasized(matching: "gr"), "**Gr**eg")
}

func testTwoLettersMatchingWithMultipleMatches() throws {
XCTAssertEqual("Gregr".emphasized(matching: "Gr"), "**Gr**egr")
XCTAssertEqual("GregR".emphasized(matching: "gr"), "**Gr**egR")
}
}

0 comments on commit 86d6b3d

Please sign in to comment.