Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.elama.bidmanager.settings.Step
- import io.circe.{HCursor, Json}
- import scala.annotation.tailrec
- object AstToSettingsUtils extends App {
- /** Extracts maxBidMaxPriceLimit from AST */
- def extractLimit(json: Json): Option[Int] = {
- @tailrec
- def f(json: Json, parent: String = "", result: Option[Int] = None): (Json, Option[Int]) = {
- val cursor = json.hcursor
- cursor.downField("kind").as[String] match {
- case Right("If") => f(cursor.downField("body").focus.get)
- case Right("SetBid") => f(cursor.downField("bid").focus.get)
- case Right(x@"Min") => f(cursor.downField("right").focus.get, x)
- case Right("Constant") => Json.Null -> Some(toPercent(cursor))
- case Right("Multiply") if parent == "Min" => f(cursor.downField("right").focus.get)
- case _ => cursor.focus.get -> result
- }
- }
- f(json)._2
- }
- /** Extracts Step value and Step Type (amount/percent) from AST */
- def extractStep(json: Json): Option[Step] = {
- @tailrec
- def f(json: Json, parent: String = "", result: Option[Step] = None): (Json, Option[Step]) = {
- val cursor = json.hcursor
- cursor.downField("kind").as[String] match {
- case Right("If") => f(cursor.downField("body").focus.get)
- case Right("SetBid") => f(cursor.downField("bid").focus.get)
- case Right("Min") => f(cursor.downField("left").focus.get)
- case Right(x@"Add") => f(cursor.downField("right").focus.get, x)
- case Right(x@"Multiply") => f(cursor.downField("right").focus.get, x)
- case Right("Constant") if parent == "Multiply" => (Json.Null, Some(Step.Percent(toPercent(cursor))))
- case Right("Constant") if parent == "Add" => (Json.Null, Some(Step.Amount(toAmount(cursor))))
- case _ => (cursor.focus.get, result)
- }
- }
- f(json)._2
- }
- private def toPercent(c: HCursor): Int = (c.downField("value").as[Double].right.get * 100).toInt - 100
- private def toAmount(c: HCursor): Double = c.downField("value").as[Double].right.get / 1000000
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement