Problem Statement: Optimizing State-Specific Task Queries

Imagine you're tasked with optimizing a complex system that manages tasks. A challenging aspect is dealing with a diverse range of task states, such as "Scheduled," "Completed," and "Canceled." The input is a JSON configuration specifying a time range and a pipe-separated list of states.


{
  "pageSize": 50,
  "page": 1,
  "filterParameters": {
    "dueFrom": "2022-01-01T00:00:00.000Z",
    "dueTo": "2024-01-01T00:00:00.000Z",
    "state": "Scheduled|Completed|Canceled"
  }
}
        

Your goal is to dynamically generate optimized queries for each state, extracting relevant tasks within the specified time range. The provided Scala code achieves this by creating a modular and extensible query builder

Key Challenges:

  1. Efficiently handling diverse task states from a pipe-separated string.
  2. Constructing individual queries for each state while maintaining code modularity.
  3. Formatting the output JSON for better readability and usability.

Proposed Solution: The Scala code employs a thoughtful design, encapsulating the query building logic into a separate object (TaskQueryBuilder). It utilizes a custom timestamp formatter and gracefully handles JSON parsing. The code elegantly splits the states, builds queries, and formats results.

Explore how this solution intelligently addresses the complexities of state-specific task queries, paving the way for a more scalable and maintainable task management system.

import java.time.format.DateTimeFormatter
import org.json.JSONObject

object TaskQueryBuilder {

  // Define a custom timestamp formatter
  val timestampFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")

  def buildQuery(state: String): Map[String, Any] = {
    val commonParams = Map(
      "dueFrom" -> "2022-01-01T00:00:00.000Z",
      "dueTo" -> "2024-01-01T00:00:00.000Z",
      "state" -> state
    )

    Map(
      "pageSize" -> 50,
      "page" -> 1,
      "filterParameters" -> commonParams
    )
  }

  // Helper method to convert TaskQuery to JSON string
  def taskQueryToJson(query: Map[String, Any], timestampFormatter: DateTimeFormatter): String = {
    val jsonString = query.map {
      case (key, value) =>
        val jsonValue = value match {
          case s: String => s""""$s""""
          case _ => value
        }
        s""""$key": $jsonValue"""
    }.mkString("{", ", ", "}")

    jsonString
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val timestampFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")

    // Given input JSON
    val inputJson =
      """
        |{
        |  "pageSize": 50,
        |  "page": 1,
        |  "filterParameters": {
        |    "dueFrom": "2022-01-01T00:00:00.000Z",
        |    "dueTo": "2024-01-01T00:00:00.000Z",
        |    "state": "Scheduled|Completed|Canceled"
        |  }
        |}
        |""".stripMargin

    // Extract the state string from the input JSON
    val jsonObject = new JSONObject(inputJson)
    val stateString = jsonObject.getJSONObject("filterParameters").getString("state")

    // Split the state string by pipe and generate separate JSONs for each state
    val states = stateString.split("\\|")

    states.foreach { state =>
      val query = TaskQueryBuilder.buildQuery(state)
      val json = TaskQueryBuilder.taskQueryToJson(query, timestampFormatter)

      println(s"$state:")
      println(json)
      println()
    }

    print(states)
  }
}
        

To view or add a comment, sign in

More articles by Jinesh Ranawat

Explore content categories