Groovy web console

subscribe to the feed Subscribe
to this


Published 1 month ago by Reinaldo Otálvaro with tags codeChallenge
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper

Coding test implemented by Reinaldo Otálvaro.

In order to traverse json input and reduce the number of iterations and memory usage with objects creation, I decided to implement a map
for storing reportable data at the same time we are reading data. 

Another aproach could be mapping input to objects like Order and Item besides the ones used here, that could allow more extensibility and 
separation of responsibilities. However, since the requirement has no more details I prefer to optimize operations for a quicker response
and less resource consumption

/*=============Global variables definition=============*/ 
def url_Json = new URL("")
def jsonSlurper = new JsonSlurper()
def product_sales_map = [:]
def json_object = jsonSlurper.parseText(url_Json.getText())
/*=============END --> Global variables definition=============*/

/*=============Functions definition=============*/

def loadProducts(json_object, product_sales_map){//Load products and keep them into a map

	for(product in json_object.products){
  Product prod = new Product(,, product.price as float)
  ProductSales ps = new ProductSales()
  product_sales_map.put(, ps)
def loadOrders(json_object, product_sales_map){//Loading orders and save them into a map with product sales details
	for(order in json_object.orders){

  for(item in order.items){
   ProductSales ps = product_sales_map.get(item.productId)
   ps.setTotalAmount(ps.getTotalAmount() + item.quantity as float)
   ps.setOrdersNumber(ps.getOrdersNumber() + 1)
   product_sales_map.put(item.productId, ps)

def printProductsReport(product_sales_map){//get detailed values saved at product sales map
	for(entry in product_sales_map){
  ProductSales ps = entry.value
  println "| " + ps.getProduct().getName() +"\t|  " + ps.getOrdersNumber() + "\t|" + ps.calculateTotalValue().trunc(2) +"\t |"

/*=============END Functions definition=============*/

class Product{
	String id
	String name
	float price
	Product(id, name, price){ = id
  this.price = price = name
class ProductSales{
	String id
	Integer ordersNumber = 0
	float totalAmount = 0
	Product product
	float calculateTotalValue(){
  return totalAmount * this.product.getPrice()
/*=============END Classes=============*/

// Print the table header
println "+---------------+-------+--------+";
println "| Product       |Orders |Total   |";
println "+---------------+-------+--------+";
loadProducts(json_object, product_sales_map)
loadOrders(json_object, product_sales_map)