Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added Chain#takeWhile and Chain#dropWhile #2956

Merged
merged 2 commits into from
Jul 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions core/src/main/scala/cats/data/Chain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,40 @@ sealed abstract class Chain[+A] {
result
}

/**
* Takes longest prefix of elements that satisfy a predicate.
* @param p The predicate used to test elements.
* @return the longest prefix of this chain whose elements all satisfy the predicate p.
*/
final def takeWhile(p: A => Boolean): Chain[A] = {
var result = Chain.empty[A]
foreachUntil { a =>
val pr = p(a)
if (pr) result = result :+ a
!pr
}
result
}

/**
* Drops longest prefix of elements that satisfy a predicate.
*
* @param p The predicate used to test elements.
* @return the longest suffix of this sequence whose first element does not satisfy the predicate p.
*/
final def dropWhile(p: A => Boolean): Chain[A] = {
@tailrec
def go(rem: Chain[A]): Chain[A] =
rem.uncons match {
case Some((a, tail)) =>
if (p(a)) go(tail)
else rem

case None => nil
}
go(this)
}

/**
* Folds over the elements from right to left using the supplied initial value and function.
*/
Expand Down
13 changes: 13 additions & 0 deletions tests/src/test/scala/cats/tests/ChainSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -224,4 +224,17 @@ class ChainSuite extends CatsSuite {
x.hashCode should ===(x.toList.hashCode)
}
}

test("Chain#takeWhile is consistent with List#takeWhile") {
forAll { (x: Chain[Int], p: Int => Boolean) =>
x.takeWhile(p).toList should ===(x.toList.takeWhile(p))
}
}

test("Chain#dropWhile is consistent with List#dropWhile") {
forAll { (x: Chain[Int], p: Int => Boolean) =>
x.dropWhile(p).toList should ===(x.toList.dropWhile(p))
}
}

}