Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chain add fromOption factory method #3808

Merged
merged 1 commit into from
Mar 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions bench/src/main/scala-2.12/cats/bench/ChainBench.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import org.openjdk.jmh.annotations.{Benchmark, Scope, State}
@State(Scope.Thread)
class ChainBench {

private val intOption = Option(1)
private val smallChain = Chain(1, 2, 3, 4, 5)
private val smallCatenable = Catenable(1, 2, 3, 4, 5)
private val smallVector = Vector(1, 2, 3, 4, 5)
Expand Down Expand Up @@ -63,4 +64,7 @@ class ChainBench {
@Benchmark def createSmallVector: Vector[Int] = Vector(1, 2, 3, 4, 5)
@Benchmark def createSmallList: List[Int] = List(1, 2, 3, 4, 5)
@Benchmark def createSmallOldChain: OldChain[Int] = OldChain(Seq(1, 2, 3, 4, 5))

@Benchmark def createChainSeqOption: Chain[Int] = Chain.fromSeq(intOption.toSeq)
@Benchmark def createChainOption: Chain[Int] = Chain.fromOption(intOption)
}
6 changes: 6 additions & 0 deletions core/src/main/scala/cats/data/Chain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,12 @@ object Chain extends ChainInstances {
case _ => c2
}

/**
* Creates a Chain from the specified option.
*/
def fromOption[A](o: Option[A]): Chain[A] =
o.fold(Chain.empty[A])(Chain.one)

/**
* Creates a Chain from the specified sequence.
*/
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/ChainSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ class ChainSuite extends CatsSuite {
}
}

test("fromOption") {
forAll { (o: Option[Int]) =>
assert(Chain.fromOption(o).toList == o.toList)
}
}

test("seq-like pattern match") {
Chain(1, 2, 3) match {
case Chain(a, b, c) => assert((a, b, c) === ((1, 2, 3)))
Expand Down