Skip to content

Instantly share code, notes, and snippets.

@psttf
Created September 17, 2020 22:42
Show Gist options
  • Save psttf/996d692341dc45adefc369a1baa4de01 to your computer and use it in GitHub Desktop.
Save psttf/996d692341dc45adefc369a1baa4de01 to your computer and use it in GitHub Desktop.
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