Skip to content

Commit

Permalink
Add SeqDecorator.replaced
Browse files Browse the repository at this point in the history
  • Loading branch information
NthPortal committed Jun 26, 2018
1 parent a479b7a commit 7f01ed6
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ The following operations are provided:

- `Seq`
- `intersperse`
- `replaced`
- `Map`
- `zipByKey` / `join` / `zipByKeyWith`
- `mergeByKey` / `fullOuterJoin` / `mergeByKeyWith` / `leftOuterJoin` / `rightOuterJoin`
Expand Down
12 changes: 12 additions & 0 deletions src/main/scala/scala/collection/decorators/SeqDecorator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,16 @@ class SeqDecorator[C, S <: HasSeqOps[C]](coll: C)(implicit val seq: S) {
def intersperse[B >: seq.A, That](start: B, sep: B, end: B)(implicit bf: BuildFrom[C, B, That]): That =
bf.fromSpecificIterable(coll)(new View.IntersperseSurround(seq(coll), start, sep, end))

/** Produces a new sequence where all occurrences of some element are replaced by
* a different element.
*
* @param elem the element to replace
* @param replacement the replacement element
* @tparam B the element type of the returned $coll.
* @return a new sequence consisting of all elements of this sequence
* except that all occurrences of `elem` are replaced by
* `replacement`
*/
def replaced[B >: seq.A, That](elem: B, replacement: B)(implicit bf: BuildFrom[C, B, That]): That =
bf.fromSpecificIterable(coll)(new collection.View.Map(seq(coll), (a: seq.A) => if (a == elem) replacement else a))
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,10 @@ class SeqDecoratorTest {

def typed[T](t: => T): Unit = ()

@Test def testReplaced(): Unit = {
val s = Seq(1, 2, 3, 2, 1)
assertEquals(s.replaced(2, 4), Seq(1, 4, 3, 4, 1))
assertEquals(s.replaced(3, 4), Seq(1, 2, 4, 2, 1))
assertEquals(s.replaced(4, 4), s)
}
}

0 comments on commit 7f01ed6

Please sign in to comment.