settingsAccountsettings
Menusettings

Q: Cappy Juice - JavaScript task

+4 votes

You will be given different juices, as strings. You will also receive quantity as a number. If you receive a juice, you already have, you must sum the current quantity of that juice, with the given one. When a juice reaches 1000 quantity, it produces a bottle. You must store all produced bottles and you must print them at the end.

Note: 1000 quantity of juice is one bottle. If you happen to have more than 1000, you must make as much bottles as you can, and store what is left from the juice.

Example: You have 2643 quantity of Orange Juice – this is 2 bottles of Orange Juice and 643 quantity left.

The input comes as array of strings. Each element holds data about a juice and quantity in the following format:
“{juiceName} => {juiceQuantity}”

Examples:

Input:
Orange => 2000
Peach => 1432
Banana => 450
Peach => 600
Strawberry => 549

Output:
Orange => 2
Peach => 2


Input:
Kiwi => 234
Pear => 2345
Watermelon => 3456
Kiwi => 4567
Pear => 5678
Watermelon => 6789

Output:
Pear => 8
Watermelon => 10
Kiwi => 4


The output is the produced bottles. The bottles are to be printed in order of obtaining the bottles. Check the second example bellow - even though we receive the Kiwi juice first, we don’t form a bottle of Kiwi juice until the 4th line, at which point we have already create Pear and Watermelon juice bottles, thus the Kiwi bottles appear last in the output.

asked in JavaScript category by user paulcabalit

1 Answer

+3 votes

JavaScript solution code:

function cappyJuice(dataRows) {
    let flavorsObj = {};
    let bottlesObj = {};
    for (let dataRow of dataRows) {
        let [juiceName, quantity] = dataRow.split(' => ');
        quantity = Number(quantity);
        if (!flavorsObj.hasOwnProperty(juiceName)) {
            flavorsObj[juiceName] = quantity;
        } else {
            flavorsObj[juiceName] += quantity;
        }
        quantity = flavorsObj[juiceName];
        if (quantity >= 1000) {
            let bottlesCount = Math.floor(quantity / 1000);
            bottlesObj[juiceName] = bottlesCount;
        }
    }


    for (let name in bottlesObj) {
        console.log(`${name} => ${bottlesObj[name]}`);
    }
}

cappyJuice([
    "Orange => 2000",
    "Peach => 1432",
    "Banana => 450",
    "Peach => 600",
    "Strawberry => 549"
]);

 

answered by user richard8502
...