Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

iliavatafov avatar iliavatafov 1 Точки

JS Advanced - Js Advanced Final Retake Exam - 10 December 2021 - 02. Vegetable store

Здравейте,

 

Не успявам да си открия грешката и имам чувството, че кодът ми е излишно сложен. Ако имате друго решение или възможност за рефакторинг ще Ви бъда много благодарен.

 

Условието на задачата е в Juge и може да го достъпите ТУК.

Решението ми е налично ТУК.

 

Поздрави,

Илия

Тагове:
0
JavaScript Advanced
Axiomatik avatar Axiomatik 2422 Точки
Best Answer

buyingVegetables : If the quantity selected by the customer for a given vegetable is greater than the quantity recorded in the array availableProducts =>  if (currentQuantity < quantity)

rottingVegetables : If the quantity selected by the customer for a given vegetable is greater than the quantity recorded in the array availableProducts => if (availableQuantity < quantity)

class VegetableStore {
    constructor(owner, location) {
        this.owner = owner;
        this.location = location;
        this.availableProducts = [];
        this._products = [];
    }

    loadingVegetables(vegetables) {
        let addedProducts = [];

        for (let element of vegetables) {
            let [type, quantity, price] = element.split(` `);

            price = Number(price);
            quantity = Number(quantity);

            const targetProduct = this.availableProducts.find(pro => pro.type == type);

            if (!targetProduct) {
                const newProduct = {
                    type,
                    price,
                    quantity,
                };

                this.availableProducts.push(newProduct);
            } else {
                const currentPrice = targetProduct.price;

                if (currentPrice < price) {
                    targetProduct.price = price;
                }

                targetProduct.quantity += quantity;
            }
        }

        // let uniq = [...new Set(addedProducts)].join(`, `);
        let uniq = [...new Set(this.availableProducts.map(p => p.type))].join(`, `);

        // return `Successfully added ${uniq}`;
        return `Successfully added ${this.availableProducts.map(p => p.type).join(', ')}`;
    }

    buyingVegetables(selectedProducts) {
        let totalPrice = 0;

        for (let element of selectedProducts) {
            let [type, quantity] = element.split(` `);
            quantity = Number(quantity);

            const targetProduct = this.availableProducts.find(pro => pro.type == type);

            // if (!this._products.includes(type)) {
            if (!targetProduct) {
                throw new Error(`${type} is not available in the store, your current bill is $${totalPrice.toFixed(2)}.`)
            }

            // let product = Object.values(p)[0];
            // let currentQuantity = Object.values(p)[1];
            // let price = Object.values(p)[2];
            let currentQuantity = targetProduct.quantity;
            let price = targetProduct.price;

            // !!! If the quantity selected by the customer for a given vegetable is greater than the quantity recorded in the array availableProducts !!!
            // if (currentQuantity <= Number(quantity)) {
            if (currentQuantity < quantity) {
                throw new Error(`The quantity ${quantity} for the vegetable ${type} is not available in the store, your current bill is $${totalPrice.toFixed(2)}.`);
            } else {
                targetProduct.quantity -= quantity;
                totalPrice += price * quantity;
            }
        }

        return `Great choice! You must pay the following amount $${totalPrice.toFixed(2)}.`;
    }

    rottingVegetable(type, quantity) {
        let result = ``;

        const targetProduct = this.availableProducts.find(pro => pro.type == type);

        // if (!this._products.includes(type)) {
        if (!targetProduct) {
            throw new Error(`${type} is not available in the store.`);
        } else {
            // let product = Object.values(p)[0];
            // let availableQuantity = Object.values(p)[1];
            let product = targetProduct.type;
            let availableQuantity = targetProduct.quantity;

            if (product == type) {

                // !!! If the submitted quantity is greater than the quantity recorded in the availableProducts array !!!
                // if (availableQuantity <= quantity) {
                if (availableQuantity < quantity) {
                    targetProduct.quantity = 0;
                    result = `The entire quantity of the ${type} has been removed.`;
                } else {
                    targetProduct.quantity -= quantity;
                    result = `Some quantity of the ${type} has been removed.`;
                }
            }

            return result;
        }
    }

    revision() {
        let result = [];

        result.push(`Available vegetables:`);

        this.availableProducts.sort((a, b) => a.price - b.price);

        for (let element of this.availableProducts) {
            result.push(`${element.type}-${element.quantity}-$${element.price}`);
        }

        result.push(`The owner of the store is ${this.owner}, and the location is ${this.location}.`);

        return result.join(`\n`);
    }
}

 

0
iliavatafov avatar iliavatafov 1 Точки

Благодаря! :)

1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.