Skip to content

Commit 8781f2f

Browse files
authored
Merge pull request scala#7 from NthPortal/collection-strawman#339/PR
Add SeqDecorator.replaced
2 parents 2837fdb + 7f01ed6 commit 8781f2f

File tree

4 files changed

+25
-0
lines changed

4 files changed

+25
-0
lines changed

.gitignore

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
classes
2+
target
3+
.idea
4+
.idea_modules
5+
*.icode
6+
project/local.sbt

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ The following operations are provided:
2222

2323
- `Seq`
2424
- `intersperse`
25+
- `replaced`
2526
- `Map`
2627
- `zipByKey` / `join` / `zipByKeyWith`
2728
- `mergeByKey` / `fullOuterJoin` / `mergeByKeyWith` / `leftOuterJoin` / `rightOuterJoin`

src/main/scala/scala/collection/decorators/SeqDecorator.scala

+12
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,16 @@ class SeqDecorator[C, S <: HasSeqOps[C]](coll: C)(implicit val seq: S) {
4141
def intersperse[B >: seq.A, That](start: B, sep: B, end: B)(implicit bf: BuildFrom[C, B, That]): That =
4242
bf.fromSpecificIterable(coll)(new View.IntersperseSurround(seq(coll), start, sep, end))
4343

44+
/** Produces a new sequence where all occurrences of some element are replaced by
45+
* a different element.
46+
*
47+
* @param elem the element to replace
48+
* @param replacement the replacement element
49+
* @tparam B the element type of the returned $coll.
50+
* @return a new sequence consisting of all elements of this sequence
51+
* except that all occurrences of `elem` are replaced by
52+
* `replacement`
53+
*/
54+
def replaced[B >: seq.A, That](elem: B, replacement: B)(implicit bf: BuildFrom[C, B, That]): That =
55+
bf.fromSpecificIterable(coll)(new collection.View.Map(seq(coll), (a: seq.A) => if (a == elem) replacement else a))
4456
}

src/test/scala/scala/collection/decorators/SeqDecoratorTest.scala

+6
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,10 @@ class SeqDecoratorTest {
3939

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

42+
@Test def testReplaced(): Unit = {
43+
val s = Seq(1, 2, 3, 2, 1)
44+
assertEquals(s.replaced(2, 4), Seq(1, 4, 3, 4, 1))
45+
assertEquals(s.replaced(3, 4), Seq(1, 2, 4, 2, 1))
46+
assertEquals(s.replaced(4, 4), s)
47+
}
4248
}

0 commit comments

Comments
 (0)