Skip to content

Commit 3962bd2

Browse files
Merge pull request #1412 from yadavan88/dropwhile-takewhile
dropWhile and takeWhile in Scala
2 parents 43b24fc + 70de5b6 commit 3962bd2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.baeldung.scala.takewhiledropwhile
2+
3+
import org.scalatest.matchers.should.Matchers
4+
import org.scalatest.wordspec.AnyWordSpec
5+
6+
class TakeWhileDropWhileUnitTest extends AnyWordSpec with Matchers {
7+
8+
private val numbersAscending = List(1, 2, 3, 4, 5, 6, 7, 8)
9+
private val numbersDescending = List(8, 7, 6, 5, 4, 3, 2, 1)
10+
private val numbersMixed = List(1, 2, 3, 4, 3, 2, 1)
11+
12+
"takeWhile" should {
13+
"take element from list till condition satisfies" in {
14+
val lessThanFive = numbersAscending.takeWhile(_ < 5)
15+
lessThanFive shouldBe List(1, 2, 3, 4)
16+
}
17+
18+
"return different elements when the element order changes" in {
19+
val lessThanFive = numbersDescending.takeWhile(_ < 5)
20+
lessThanFive shouldBe Nil
21+
}
22+
23+
"stop taking as soon as the first failure in predicate" in {
24+
val lessThanThree = numbersMixed.takeWhile(_ < 3)
25+
lessThanThree shouldBe List(1, 2)
26+
}
27+
28+
"take all elements if the predicate is satisfied for all" in {
29+
val positive = numbersAscending.takeWhile(_ > 0)
30+
positive shouldBe numbersAscending
31+
}
32+
33+
}
34+
35+
"dropWhile" should {
36+
"drop the elements from the list until the predicate is true" in {
37+
val dropLessThan5 = numbersAscending.dropWhile(_ < 5)
38+
dropLessThan5 shouldBe List(5, 6, 7, 8)
39+
}
40+
41+
"dropWhile behavior changes with the order" in {
42+
val dropLessThan5 = numbersDescending.dropWhile(_ < 5)
43+
dropLessThan5 shouldBe numbersDescending
44+
}
45+
}
46+
47+
}

0 commit comments

Comments
 (0)