Skip to content

Add groupMapReduce method to IterableOnceOps #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 5, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/main/scala/scala/collection/IteratorExtensions.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/

package scala.collection

object IteratorExtensions {
implicit class IteratorExtensionsOps[A](private val iter: Iterator[A]) extends AnyVal {
/**
* Partitions this Iterator into a map according to a discriminator function `key`. All the values that
* have the same discriminator are then transformed by the `value` function and then reduced into a
* single value with the `reduce` function.
*
* {{{
* def occurrences[A](as: Iterator[A]): Map[A, Int] =
* as.groupMapReduce(identity)(_ => 1)(_ + _)
* }}}
*
* @note This will force the evaluation of the Iterator.
*/
def groupMapReduce[K, B](key: A => K)(f: A => B)(reduce: (B, B) => B): immutable.Map[K, B] = {
val m = mutable.Map.empty[K, B]
iter.foreach { elem =>
m.updateWith(key = key(elem)) {
case Some(b) => Some(reduce(b, f(elem)))
case None => Some(f(elem))
}
}
m.to(immutable.Map)
}
}
}
29 changes: 29 additions & 0 deletions src/test/scala/scala/collection/TestIteratorExtensions.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/

package scala.collection

import org.junit.Assert._
import org.junit.Test
import IteratorExtensions._

final class TestIteratorExtensions {
@Test
def groupMapReduce(): Unit = {
def occurrences[A](as: Seq[A]): Map[A, Int] =
as.iterator.groupMapReduce(identity)(_ => 1)(_ + _)

val xs = Seq('a', 'b', 'b', 'c', 'a', 'a', 'a', 'b')
val expected = Map('a' -> 4, 'b' -> 3, 'c' -> 1)
assertEquals(expected, occurrences(xs))
}
}