From aa469525312cd9d445c6c55ac2637b659509b25d Mon Sep 17 00:00:00 2001 From: James Strachan Date: Fri, 23 Dec 2011 16:48:22 +0000 Subject: [PATCH] implemented containerType.count(predicate) --- stdlib/ktSrc/JavaIterables.kt | 10 ++++++++++ testlib/test/CollectionTest.kt | 7 ++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/stdlib/ktSrc/JavaIterables.kt b/stdlib/ktSrc/JavaIterables.kt index c10479d2f10..438b29dc388 100644 --- a/stdlib/ktSrc/JavaIterables.kt +++ b/stdlib/ktSrc/JavaIterables.kt @@ -22,6 +22,16 @@ inline fun java.lang.Iterable.all(predicate: (T)-> Boolean) : Boolean { return true } +/** Returns the number of items which match the given predicate */ +inline fun java.lang.Iterable.count(predicate: (T)-> Boolean) : Int { + var answer = 0 + for (elem in this) { + if (predicate(elem)) + answer += 1 + } + return answer +} + /** Returns the first item in the collection which matches the given predicate or null if none matched */ inline fun java.lang.Iterable.find(predicate: (T)-> Boolean) : T? { for (elem in this) { diff --git a/testlib/test/CollectionTest.kt b/testlib/test/CollectionTest.kt index 1c4ef83d11d..926c300862c 100644 --- a/testlib/test/CollectionTest.kt +++ b/testlib/test/CollectionTest.kt @@ -29,6 +29,12 @@ class CollectionTest() : TestSupport() { } } + fun testCount() { + assertEquals(1, data.count{it.startsWith("b")}) + // TODO size should implement size property to be polymorphic with collections + assertEquals(2, data.count{it.length == 3}) + } + fun testFilter() { val foo = data.filter{it.startsWith("f")} @@ -153,5 +159,4 @@ class CollectionTest() : TestSupport() { } } } - } \ No newline at end of file