Skip to content

Commit

Permalink
🎨 rework parsers
Browse files Browse the repository at this point in the history
  • Loading branch information
twentylemon committed Dec 17, 2024
1 parent f5eb7ef commit 03ba748
Showing 1 changed file with 27 additions and 29 deletions.
56 changes: 27 additions & 29 deletions src/main/scala/org/lemon/advent/lib/parse.scala
Original file line number Diff line number Diff line change
@@ -1,31 +1,29 @@
package org.lemon.advent.lib

object Parse:
object Num:
def unapply[T: Numeric](s: String): Option[T] = summon[Numeric[T]].parseString(s)

private def splitParse[T: Numeric](s: String, delimeter: String): Option[Seq[T]] =
Some(s.split(delimeter).map(_.trim).toSeq.flatMap(Num.unapply[T]))

object NumCsv:
def unapply[T: Numeric](s: String): Option[Seq[T]] = splitParse(s, ",")

object NumWsv:
def unapply[T: Numeric](s: String): Option[Seq[T]] = splitParse(s, "\\s+")

object Chunk:
def unapply(s: String): Option[Seq[String]] = Some(s.split("\n\n").toSeq)

object Int:
def unapply(s: String): Option[Int] = Num.unapply(s)
object IntCsv:
def unapply(s: String): Option[Seq[Int]] = NumCsv.unapply[Int](s)
object IntWsv:
def unapply(s: String): Option[Seq[Int]] = NumWsv.unapply[Int](s)

object Long:
def unapply(s: String): Option[Long] = Num.unapply(s)
object LongCsv:
def unapply(s: String): Option[Seq[Long]] = NumCsv.unapply[Long](s)
object LongWsv:
def unapply(s: String): Option[Seq[Long]] = NumWsv.unapply[Long](s)
object Chunk:
def unapplySeq(s: String): Option[Seq[String]] = Some(s.split("\n\n").toSeq)

object Csv:
private val delimeter = ","
def unapply[T: Numeric](s: String): Option[Seq[T]] = Some(splitParse(s, delimeter).flatMap(Num.unapply[T]))
def unapply(s: String): Option[Seq[String]] = Some(splitParse(s, delimeter))

object Wsv:
private val delimeter = "\\s+"
def unapply[T: Numeric](s: String): Option[Seq[T]] = Some(splitParse(s, delimeter).flatMap(Num.unapply[T]))
def unapply(s: String): Option[Seq[String]] = Some(splitParse(s, delimeter))

extension (int: Int.type)
def unapply(s: String): Option[Int] = Num.unapply(s)

extension (long: Long.type)
def unapply(s: String): Option[Long] = Num.unapply(s)

extension (bigint: BigInt.type)
def unapply(s: String): Option[BigInt] = Num.unapply(s)

object Num:
def unapply[T: Numeric](s: String): Option[T] = summon[Numeric[T]].parseString(s)

private def splitParse(s: String, delimeter: String): Seq[String] =
s.split(delimeter).map(_.trim).toSeq

0 comments on commit 03ba748

Please sign in to comment.