added support for fold() along with a handy expect() test method (like scalatest)
This commit is contained in:
@@ -81,6 +81,20 @@ inline fun <T> java.lang.Iterable<T>.foreach(operation: (element: T) -> Unit) {
|
|||||||
operation(elem)
|
operation(elem)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Folds all the values from from left to right using the initial value to perform the operation on sequential pairs of values
|
||||||
|
*
|
||||||
|
* For example to sum together all numeric values in a collection of numbers it would be
|
||||||
|
* {code}numbers.fold(0){(a, b) -> a + b}{code}
|
||||||
|
*/
|
||||||
|
inline fun <T> java.lang.Iterable<T>.fold(initial: T, operation: (it: T, it2: T) -> T): T {
|
||||||
|
var answer = initial
|
||||||
|
for (elem in this) {
|
||||||
|
answer = operation(answer, elem)
|
||||||
|
}
|
||||||
|
return answer
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Iterates through the collection performing the transformation on each element and using the result
|
* Iterates through the collection performing the transformation on each element and using the result
|
||||||
* as the key in a map to group elements by the result
|
* as the key in a map to group elements by the result
|
||||||
|
|||||||
@@ -127,6 +127,21 @@ class CollectionTest() : TestSupport() {
|
|||||||
assertEquals(6, count)
|
assertEquals(6, count)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun testFold() {
|
||||||
|
expect(10) {
|
||||||
|
val numbers = arrayList(1, 2, 3, 4)
|
||||||
|
|
||||||
|
// TODO would be nice to be able to write this as this
|
||||||
|
//numbers.fold(0){it + it2}
|
||||||
|
numbers.fold(0){(it, it2) -> it + it2}
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(0) {
|
||||||
|
val numbers = arrayList<Int>()
|
||||||
|
numbers.fold(0){(it, it2) -> it + it2}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun testGroupBy() {
|
fun testGroupBy() {
|
||||||
val words = arrayList("a", "ab", "abc", "def", "abcd")
|
val words = arrayList("a", "ab", "abc", "def", "abcd")
|
||||||
/*
|
/*
|
||||||
|
|||||||
@@ -97,6 +97,15 @@ fun assertNull(actual: Any?, message: String = "") {
|
|||||||
Assert.assertNull(message, actual)
|
Assert.assertNull(message, actual)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun <T> expect(expected: T, block: ()-> T) {
|
||||||
|
expect(expected, block.toString(), block)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun <T> expect(expected: T, message: String, block: ()-> T) {
|
||||||
|
val actual = block()
|
||||||
|
assertEquals(expected, actual, message)
|
||||||
|
}
|
||||||
|
|
||||||
fun fails(block: ()-> Any) {
|
fun fails(block: ()-> Any) {
|
||||||
try {
|
try {
|
||||||
block()
|
block()
|
||||||
|
|||||||
Reference in New Issue
Block a user