Groovy web console

subscribe to the feed Subscribe
to this
site

Tailorsoft Coding Test

Published 1 week ago by Juan Camilo Gutierrez Fuentes
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.*
import java.math.BigDecimal;

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

// declare object JSON type
def jsonSlurper = new JsonSlurper()
def objJson = jsonSlurper.parse(url_Json)

// separe products and orders in 2 objects
def objProducts = objJson.products
def objOrders = objJson.orders

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

// getting products in orders
def objTableContents = new ArrayList<Object>();
for(int i = 0; i < objProducts.size; i++){
    for(int j = 0; j < objOrders.size; j++){
        for(int k = 0; k < objOrders.items[j].size; k++){
            if(objProducts[i].id == objOrders.items[j].productId[k]){
                objTableContents.add(objOrders.items[j][k]);
            }
        }
    }
}
// Print the table content
for(Object item:objTableContents){
    BigDecimal total = 0;
    def nameProduct = "";
    def c = 0;
    for(int i = 0; i < objProducts.size; i++){
        if(item.productId==objProducts[i].id){
            nameProduct = objProducts[i].name;
            total = objProducts[i].price.toDouble() * item.quantity;
        }
    }
    println "| "+nameProduct+'\t'+"|\t "+ item.quantity +"| "+ total.setScale(2, BigDecimal.ROUND_HALF_EVEN)+"\t|";
    println "+---------------+---------+-------------+";
}