Last active
August 29, 2015 14:18
-
-
Save bigjason/c68149e023f8caf639d6 to your computer and use it in GitHub Desktop.
Extension to add missing `Map` transformers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mapops { | |
implicit class DayOneMapOps[A, +B](wrapped: Map[A, B]) { | |
// Scalaz has `mapKeys` to just change keys | |
// Scala has `mapValues` to just change values | |
// Scala has `transform` to just change values but provides key as a parameter | |
/** | |
* This function transforms all the keys and values of mappings contained in this map with function `f`. | |
* | |
* @param f A function over keys and values returning a Tuple of new key -> value pair | |
* @return the updated map | |
*/ | |
def transformAll[C, D, That](f: (A, B) => (C, D))(implicit bf: CanBuildFrom[Map[A, B], (C, D), That]): That = { | |
val builder = bf.apply() | |
wrapped.foreach { case (oldKey, oldValue) => | |
builder += f(oldKey, oldValue) | |
} | |
builder.result() | |
} | |
/** | |
* This function transforms all the keys and values of mappings contained in this map with function `f` to | |
* a [[scala.Seq]]. | |
* | |
* @param f A function over keys and values returning a single value | |
* @return the new [[scala.Seq]] | |
*/ | |
def mapToSeq[C](f: (A, B) => C): Seq[C] = | |
wrapped.foldRight(Vector.empty[C]) { (pair, result) => | |
val (key, value) = pair | |
result :+ f(key, value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment