scala-collection-contrib icon indicating copy to clipboard operation
scala-collection-contrib copied to clipboard

MultiDict add many values at once for a single key

Open ifazk opened this issue 3 years ago • 0 comments
trafficstars

Hi, I've recently started using mutable.MultiDict, but I often found myself using this pattern.

iterable.foreach(v => dict.addOne(k,v))

Could we add a function to add many values all at once for a single key instead of one at a time?

I was thinking of something like the following:

// mutable
  def addMany(key: K, values: Iterable[V]): this.type = {
    elems.updateWith(k) {
      case None     => Some(Set.from(values))
      case Some(vs) => Some(vs ++= values)
    }
    this
  }
// immutable
  def addMany(key: K, values: Iterable[V]): MultiDict[K, V] =
    new MultiDict(elems.updatedWith(key) {
      case None     => Some(Set.from(values))
      case Some(vs) => Some(vs ++ values)
    })

We might also want to skip updates if the iterables are empty.

ifazk avatar Feb 04 '22 21:02 ifazk