-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathChapter12Spec.scala
104 lines (82 loc) · 2.76 KB
/
Chapter12Spec.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import Chapter12._
import org.scalatest.{FlatSpec, Matchers}
class Chapter12Spec extends FlatSpec with Matchers {
"values" should "yield a collection of function inputs and outputs in a given range" in {
//when
val result: Seq[(Int, Int)] = values(x => x * x, -5, 5)
//then
result shouldBe Seq((-5, 25), (-4, 16), (-3, 9), (-2, 4), (-1, 1), (0, 0),
(1, 1), (2, 4), (3, 9), (4, 16), (5, 25))
}
"largestElement" should "return the largest element of an array with reduceLeft" in {
//given
val arr = Array(5, 6, 1, 0, -2, 3, -1)
//when
val result: Int = largestElement(arr)
//then
result shouldBe 6
}
"factorial" should "be implemented using to and reduceLeft" in {
//when & then
factorial(-1) shouldBe 1
factorial(0) shouldBe 1
factorial(1) shouldBe 1
factorial(5) shouldBe 120
}
"factorial2" should "be implemented using to and foldLeft" in {
//when & then
factorial2(-1) shouldBe 1
factorial2(0) shouldBe 1
factorial2(1) shouldBe 1
factorial2(5) shouldBe 120
}
"largest" should "return the largest value of a function within a given sequence of inputs" in {
//when
val result: Int = largest(x => 10 * x - x * x, 1 to 10)
//then
result shouldBe 25
}
"largestAt" should "return the input at which the output is largest" in {
//when
val result: Int = largestAt(x => 10 * x - x * x, 1 to 10)
//then
result shouldBe 5
}
"adjustToPair" should "return the function that operates on a pair" in {
//when & then
adjustToPair(_ * _)((6, 7)) shouldBe 42
}
"mapPairs" should "compute the sums of the elements in pairs" in {
//given
val pairs = (1 to 10) zip (11 to 20)
//when
val result: Seq[Int] = mapPairs(pairs, _ + _)
result shouldBe Seq(12, 14, 16, 18, 20, 22, 24, 26, 28, 30)
}
"correspondsLen" should "check that strings have the lengths from integers array" in {
//when & then
correspondsLen(Array(""), Array(0)) shouldBe true
correspondsLen(Array(""), Array(1)) shouldBe false
correspondsLen(Array("a"), Array(1)) shouldBe true
correspondsLen(Array("a"), Array(2)) shouldBe false
correspondsLen(Array("a", "bb", "ccc"), Array(1, 2, 3)) shouldBe true
correspondsLen(Array("a", "bb", "ccc"), Array(1, 2, 3, 4)) shouldBe false
correspondsLen(Array("a", "bb", "ccc"), Array(1, 2)) shouldBe false
}
"corresponds2" should "be implemented without currying" in {
corresponds2(Array("a"), Array(1), (a: String, b: Int) => a.length == b) shouldBe true
}
"unless" should "work just like if, but with an inverted condition" in {
//when & then
var a = 0
unless(a == 1) {
a = 1
}
a shouldBe 1
var b = 0
unless(b == 0) {
b = 1
}
b shouldBe 0
}
}