Skip to content

Commit

Permalink
Merge pull request #269 from henricook/string-contains
Browse files Browse the repository at this point in the history
Support case insensitive string contains
  • Loading branch information
rossabaker authored May 11, 2023
2 parents 899559d + c4a0a8f commit bfb7f1f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
11 changes: 11 additions & 0 deletions core/src/main/scala/org/typelevel/ci/CIString.scala
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@ final class CIString private (override val toString: String)

def length: Int = toString.length

def contains(needle: CIString): Boolean = {
val needleLength = needle.toString.length
val haystack = toString
// There's no point searching haystack indexes beyond which the substring is too small to ever match the needle
val maxHaystackStartingIndex = haystack.length - needleLength

(0 to maxHaystackStartingIndex).exists { i =>
haystack.regionMatches(true, i, needle.toString, 0, needleLength)
}
}

@deprecated("Use toString", "0.1.0")
def value: String = toString
}
Expand Down
25 changes: 25 additions & 0 deletions tests/shared/src/test/scala/org/typelevel/ci/CIStringSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,31 @@ class CIStringSuite extends DisciplineSuite {
})
}

test("contains lowercase to lowercase is true if matching") {
assert(CIString("hello there").contains(CIString("hello there")))
assert(CIString("hello there").contains(CIString("hello")))
}

test("contains lowercase to lowercase is false if not matching") {
assertEquals(CIString("hello there").contains(CIString("guten arben")), false)
}

test("contains lowercase to mixed case is false if not matching") {
assertEquals(CIString("hello there").contains(CIString("GUTEN ARBEN")), false)
}

test("contains mixed to mixed case is true if matching") {
assert(CIString("HELLO there").contains(CIString("hellO ThErE")))
}

test("contains uppercase to mixed case is true if matching") {
assert(CIString("HELLO THERE").contains(CIString("hellO ThErE")))
}

test("contains uppercase to mixed case is false if not matching") {
assertEquals(CIString("HELLO THERE").contains(CIString("GUTEN arben")), false)
}

checkAll("Order[CIString]", OrderTests[CIString].order)
checkAll("Hash[CIString]", HashTests[CIString].hash)
checkAll("LowerBounded[CIString]", LowerBoundedTests[CIString].lowerBounded)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@ package org.typelevel.ci
import munit.FunSuite

class TurkeySuite extends FunSuite {
test("passes the Turkey test") {
test("equals passes the Turkey test") {
assertEquals(CIString("i"), CIString("I"))
}

test("contains passes the Turkey test") {
assert(CIString("i").contains(CIString("I")))
assert(CIString("I").contains(CIString("i")))
}
}

0 comments on commit bfb7f1f

Please sign in to comment.