|
| 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 | + "takeWhile" should { |
| 9 | + "take element from list till condition satisfies" in { |
| 10 | + val numbers = List(1, 2, 3, 4, 5, 6, 7, 8) |
| 11 | + val lessThanFive = numbers.takeWhile(_ < 5) |
| 12 | + lessThanFive shouldBe List(1, 2, 3, 4) |
| 13 | + } |
| 14 | + |
| 15 | + "return different elements when the element order changes" in { |
| 16 | + val numbers = List(8, 7, 6, 5, 4, 3, 2, 1) |
| 17 | + val lessThanFive = numbers.takeWhile(_ < 5) |
| 18 | + lessThanFive shouldBe Nil |
| 19 | + } |
| 20 | + |
| 21 | + "stop taking as soon as the first failure in predicate" in { |
| 22 | + val numbers = List(1, 2, 3, 4, 3, 2, 1) |
| 23 | + val lessThanThree = numbers.takeWhile(_ < 3) |
| 24 | + lessThanThree shouldBe List(1, 2) |
| 25 | + } |
| 26 | + |
| 27 | + } |
| 28 | + |
| 29 | + "dropWhile" should { |
| 30 | + "drop the elements from the list until the predicate is true" in { |
| 31 | + val numbers = List(1, 2, 3, 4, 5, 6, 7, 8) |
| 32 | + val dropLessThan5 = numbers.dropWhile(_ < 5) |
| 33 | + dropLessThan5 shouldBe List(5, 6, 7, 8) |
| 34 | + } |
| 35 | + |
| 36 | + "dropWhile behavior changes with the order" in { |
| 37 | + val numbers = List(8, 7, 6, 5, 4, 3, 2, 1) |
| 38 | + val dropLessThan5 = numbers.dropWhile(_ < 5) |
| 39 | + dropLessThan5 shouldBe numbers |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | +} |
0 commit comments