diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6bf5f1a --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +classes +target +.idea +.idea_modules +*.icode +project/local.sbt \ No newline at end of file diff --git a/README.md b/README.md index 978cdce..4f64081 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ The following operations are provided: - `Seq` - `intersperse` + - `replaced` - `Map` - `zipByKey` / `join` / `zipByKeyWith` - `mergeByKey` / `fullOuterJoin` / `mergeByKeyWith` / `leftOuterJoin` / `rightOuterJoin` diff --git a/src/main/scala/scala/collection/decorators/SeqDecorator.scala b/src/main/scala/scala/collection/decorators/SeqDecorator.scala index d9e4aa3..4dce7a2 100644 --- a/src/main/scala/scala/collection/decorators/SeqDecorator.scala +++ b/src/main/scala/scala/collection/decorators/SeqDecorator.scala @@ -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)) } diff --git a/src/test/scala/scala/collection/decorators/SeqDecoratorTest.scala b/src/test/scala/scala/collection/decorators/SeqDecoratorTest.scala index 26acb32..de7f1d2 100644 --- a/src/test/scala/scala/collection/decorators/SeqDecoratorTest.scala +++ b/src/test/scala/scala/collection/decorators/SeqDecoratorTest.scala @@ -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) + } }