Created
September 17, 2020 22:42
-
-
Save psttf/996d692341dc45adefc369a1baa4de01 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package syntax | |
import cats.data.NonEmptyList | |
import cats.syntax.reducible._ | |
package object catssyntax { | |
object InitLastNel { | |
def unapply[T](nel: NonEmptyList[T]): Option[(List[T], T)] = | |
(nel.init, nel.last).some | |
} | |
implicit class NonEmptyListOps[T](val nel: NonEmptyList[T]) extends AnyVal { | |
/** | |
* [[scala.collection.IterableLike#grouped]] for [[NonEmptyList]] | |
*/ | |
def grouped(groupSize: Int): NonEmptyList[NonEmptyList[T]] = | |
nel.reduceLeftTo(elem => NonEmptyList.one(NonEmptyList.one(elem))) { | |
case (InitLastNel(initGroups, lastGroup), elem) | |
if lastGroup.size < groupSize => | |
NonEmptyList.ofInitLast(initGroups, lastGroup.append(elem)) | |
case (groups, elem) => | |
groups.append(NonEmptyList.one(elem)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment