Skip to content

Instantly share code, notes, and snippets.

@bigjason
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bigjason/c68149e023f8caf639d6 to your computer and use it in GitHub Desktop.
Save bigjason/c68149e023f8caf639d6 to your computer and use it in GitHub Desktop.
Extension to add missing `Map` transformers.
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