Groovy web console

subscribe to the feed Subscribe
to this
site

Tailorsoft test

Published 4 weeks ago by Miguel Campuzano with tags Groovy
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper


static getNumberOfOrdersPlacedForProduct(productId, orders) {
    def cont = 0
    for (i in 0..<orders.size()) {
        if (orders.items.productId.get(i).contains(productId)) {
            cont++
        }
    }
    return cont
}

static getTotalSpentOnProductAcrossOrders(productId, productPrice, orders) {
    def total = 0
    for (i in 0..<orders.size()) {
        if (orders.items.productId.get(i).contains(productId)) {
            def index = orders.items.productId.get(i).indexOf(productId)
            total += orders.items.quantity.get(i)[index] * Float.parseFloat(productPrice)
        }
    }
    return total
}

static void main(String[] args) {
    // Print the table header
    println "+------------------+------------+-------------+"
    println "|    Product       |  Orders    |    Total    |"
    println "+------------------+------------+-------------+"
    def url_Json = new URL("https://www.tailorsoft.co/sample.json")
    def connection = url_Json.openConnection()
    connection.requestMethod = 'GET'
    String format = "%-40s%s%n";
    if (connection.responseCode == 200) {
        def list = new JsonSlurper().parseText(connection.content.text)
        for (int i = 0; i < list.products.size(); i++) {
            print "  " + list.products.name.get(i)
            print "\t\t" + getNumberOfOrdersPlacedForProduct(list.products.id.get(i), list.orders)
            print "\t\t" + getTotalSpentOnProductAcrossOrders(list.products.id.get(i), list.products.price.get(i), list.orders)
            println ""
        }
    } else {
        println "Problem with connection"
    }
}