Skip to content

Commit

Permalink
Merge pull request scala#7 from NthPortal/collection-strawman#339/PR
Browse files Browse the repository at this point in the history
Add SeqDecorator.replaced
  • Loading branch information
julienrf authored Jun 26, 2018
2 parents 2837fdb + 7f01ed6 commit 8781f2f
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
classes
target
.idea
.idea_modules
*.icode
project/local.sbt
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 8781f2f

Please sign in to comment.