Groovy web console

subscribe to the feed Subscribe
to this
site

Coding test

Published 1 month ago by Camila Vásquez
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper 

def url_Json = new URL("https://www.tailorsoft.co/sample.json")

// Print the table header
println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";

def jsonSlurper = new JsonSlurper() 
def object = jsonSlurper.parseText(url_Json.text)
for (product in object.products){
    def total_items = 0
    def total_sales = 0
    for (order in object.orders){
        for (item in order.items){
            if (item.productId == product.id){
                total_items += 1
                total_sales += item.quantity
            }
        }
    }
    
    total_sales = String.valueOf(Float.valueOf(product.price) * total_sales)
    if (total_sales.length() > 4){
        total_sales = total_sales.substring(0,5)
    }
    total_items = String.valueOf(total_items)
    description = [product.name + ' '*(13 - product.name.length()),
                   total_items,
                   ' '*(11 - total_sales.length())+total_sales]
    println( sprintf('| %1$s| %2$s       |%3$s |', description) )
}
println "+--------------+---------+------------+";