Groovy web console

subscribe to the feed Subscribe
to this
site

Tailorsoft Coding Test

Published 2 weeks ago by Brayam Saavedra with tags TailorSoft Test
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper

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

//Create Json Slurper instance
JsonSlurper slurper = new JsonSlurper();

//Create object from provided url
Object object = slurper.parse(url_Json);

//Store data as a Map where the key is the ID of the products
def products = [:]
for (product in object.products){
    products.put(product.id, [name:product.name, price: product.price]);
}

//Get all orders and loop through them to determine how many times a product is ordered
def orders = object.orders;
products.each { key, value ->         
    def cnt_products = 0;
    def cnt_orders = 0;
    for (ord in object.orders){
        for (item in ord.items){
            if (item.productId == key){
                cnt_products += item.quantity;
                cnt_orders += 1;
            }
        }        
    }
    
    //store values into the map
    products[key].cnt_products = cnt_products;
    products[key].cnt_orders = cnt_orders;
}

// Print the table header
println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";
products.each {product->
    //Print the product name and set the spacing
    print "| $product.value.name" + " ".multiply(13 - product.value.name.length()) + "|";

    //Print the number of orders placed for a product and set the spacing
    print " ".multiply(8 - product.value.cnt_orders.toString().length()) + "$product.value.cnt_orders" + " |";

    //Calculate the total dollar spent on a product and set spacing
    double totalSpentProduct = (Double.parseDouble(product.value.price)*product.value.cnt_products).round(2);
    println " ".multiply(12 - totalSpentProduct.toString().length()) + totalSpentProduct.toString() + "|";
    println "+--------------+---------+------------+";
}