/    Sign up×
Community /Pin to ProfileBookmark

JavaScript (OOP)

Hi all. I am learning JS, and got the following task. I can do it by functions, but it is hard for me to code it by OOP (I am learning OOP now).
If somebody could just give me some hints about structure of the code, and how to implement method **addExtraIngredient(ingredient)**, it would be very nice. Here is the task:

Use constructor function.
Create pizza of different sizes and different types:
Sizes:

  • S (+50 UAH)

  • M (+75 UAH)

  • L (+100 UAH)
    Types:

  • VEGGIE (+50 UAH)

  • MARGHERITA (+60 UAH)

  • PEPPERONI (+70 UAH)
    You can add extra ingredients to the pizza:
    Extra ingredients:

  • CHEESE (+7 UAH)

  • TOMATOES (+5 UAH)

  • MEAT (+9 UAH)
  • The program should calculate the cost of a pizza and info about your pizza.
    The code must be error-proof. If you pass the wrong type of pizza, for example,
    or the wrong kind of ingredient, an exception should be thrown (use **PizzaException** class).

    ### Pizza Class Description

    **Class members:**

  • properties (size and type are required):
    _size_: size of pizza (must be from the _allowedSizes_ property)
    _type_: type of pizza (must be from the _allowedTypes_ property)

  • methods:
    _addExtraIngredient(ingredient)_: add extra ingredient. Method must:


  • 1.

    Accept only one parameter, otherwise show an error


  • 2.

    Check if such an ingredient exists in _allowedIngredients_, if does not exist,
    show an error


  • 3.

    Check if such an ingredient already exists; if there is, show error (you can add
    one ingredient only once)
    _removeExtraIngredient(ingredient)_: remove extra ingredient. Method must:


  • 1.

    Accept only one parameter, otherwise show an error


  • 2.

    Check if such an ingredient exists in allowedIngredients, if does not exist,
    show an error


  • 3.

    Check if such an ingredient has already been added, if it not added, show an
    error, otherwise remove ingredient

  • _getSize()_: returns size of pizza
    _getPrice()_: returns total price
    _getPizzaInfo()_: returns size, type, extra ingredients and price of pizza

    ### PizzaExeption Class Description

    Provides information about an error while working with a Pizza. Details are stored in the log
    property.
    Class members:

  • properties:
    • log: information about an error while working with a Pizza.
  • What I managed to code is below:

    “`
    ‘use strict’;

    /**
    * Class
    * @constructor
    * @param size – size of pizza
    * @param type – type of pizza
    * @throws {PizzaException} – in case of improper use
    */
    function Pizza(size, type) {
    let totalPrice = 0;
    this.size = size;
    this.type = type;

    this.getPrice = function () {
    // this.totalPrice = size.price + type.price + totalPrice ;
    return size.price + type.price + totalPrice;
    }

    this.addExtraIngredient = function (ingredient) {
    this.totalPrice = totalPrice + ingredient.price;
    return this.totalPrice;
    }

    // this.getSize = function () {
    // return size.size;
    // }

    // this.getPizzaInfo = function () {
    // const report = `
    // The size of pizza: ${size.size}, type: ${type.type}, extra ingredients: ${true}, total price: ${this.getPrice()}
    // `;
    // return report;
    // }

    }

    /* Sizes, types and extra ingredients */
    Pizza.SIZE_S = {size: ‘small’, price: 50};
    Pizza.SIZE_M = {size: ‘medium’, price: 75};
    Pizza.SIZE_L = {size: ‘large’, price: 100};

    Pizza.TYPE_VEGGIE = {type: ‘veggy’, price: 50};
    Pizza.TYPE_MARGHERITA = {type: ‘margherita’, price: 60};
    Pizza.TYPE_PEPPERONI = {type: ‘pepperoni’, price: 70};

    Pizza.EXTRA_TOMATOES = {extra: ‘tomatoes’, price: 5};
    Pizza.EXTRA_CHEESE = {extra: ‘cheese’, price: 7};
    Pizza.EXTRA_MEAT = {extra: ‘meat’, price: 9};

    /* Allowed properties */
    Pizza.allowedSizes = ;
    Pizza.allowedTypes = ;
    Pizza.allowedExtraIngredients = [Pizza.EXTRA_TOMATOES, Pizza.EXTRA_CHEESE, Pizza.EXTRA_MEAT ];

    /**
    * Provides information about an error while working with a pizza.
    * details are stored in the log property.
    * @constructor
    */
    function PizzaException() {}

    /* It should work */
    // // small pizza, type: veggie
    let pizza = new Pizza(Pizza.SIZE_S, Pizza.TYPE_VEGGIE);
    // // add extra meat
    pizza.addExtraIngredient(Pizza.EXTRA_MEAT);
    console.log(pizza.totalPrice);
    // // check price
    console.log(`Price: ${pizza.getPrice()} UAH`); //=> Price: 109 UAH
    // // add extra corn
    // pizza.addExtraIngredient(Pizza.EXTRA_CHEESE);
    // // add extra corn
    // pizza.addExtraIngredient(Pizza.EXTRA_TOMATOES);
    // // check price
    // console.log(`Price with extra ingredients: ${pizza.getPrice()} UAH`); // Price: 121 UAH
    // // check pizza size
    // console.log(`Is pizza large: ${pizza.getSize() === Pizza.SIZE_L}`); //=> Is pizza large: false
    // // remove extra ingredient
    // pizza.removeExtraIngredient(Pizza.EXTRA_CHEESE);
    // console.log(`Extra ingredients: ${pizza.getExtraIngredients().length}`); //=> Extra ingredients: 2
    // console.log(pizza.getPizzaInfo()); //=> Size: SMALL, type: VEGGIE; extra ingredients: MEAT,TOMATOES; price: 114UAH.

    // examples of errors
    // let pizza = new Pizza(Pizza.SIZE_S); // => Required two arguments, given: 1

    // let pizza = new Pizza(Pizza.SIZE_S, Pizza.SIZE_S); // => Invalid type

    // let pizza = new Pizza(Pizza.SIZE_S, Pizza.TYPE_VEGGIE);
    // pizza.addExtraIngredient(Pizza.EXTRA_MEAT);
    // pizza.addExtraIngredient(Pizza.EXTRA_MEAT); // => Duplicate ingredient

    // let pizza = new Pizza(Pizza.SIZE_S, Pizza.TYPE_VEGGIE);
    // pizza.addExtraIngredient(Pizza.EXTRA_MEAT); // => Invalid ingredient

    “`

    to post a comment

    1 Comments(s)

    Copy linkTweet thisAlerts:
    @LarisaauthorNov 29.2021 — Finally I managed to do the task:

    ``'use strict';<i>
    </i>function Pizza(size, type) {
    const requiredArguments = 2;
    if (arguments.length !== requiredArguments) {
    throw new PizzaException(
    Required two arguments, given: ${arguments.length})
    }

    if (!Pizza.allowedTypes.includes(type) || !Pizza.allowedSizes.includes(size)) {
    throw new PizzaException('Invalid type');
    }

    const negativeIndex = -1;
    let _size = size;
    let extrasType = [];
    let extrasPrice = [];
    this.type = type;

    Pizza.prototype.getSize = function () {
    return _size.size;
    };

    Pizza.prototype.getPrice = function () {
    return _size.price + this.type.price;
    };

    Pizza.prototype.addExtraIngredient = function (ingredient) {
    if (!ingredient) {
    throw new PizzaException('Invalid ingredient')
    }

    if (type.type === 'VEGGIE' &amp;&amp; ingredient.extra === 'MEAT') {
    throw new PizzaException('Invalid ingredient');
    }

    if (extrasType.includes(ingredient.extra)) {
    throw new PizzaException('Duplicate ingredient');
    }

    extrasPrice.push(_size.price += ingredient.price);
    extrasType.push(ingredient.extra);
    return _size.price;
    };

    Pizza.prototype.removeExtraIngredient = function (ingredient) {
    extrasPrice.pop(this.type.price -= ingredient.price);
    const index = extrasType.indexOf(ingredient.extra);
    if (index &gt; negativeIndex) {
    extrasType.splice(index, 1);
    }
    return this.type.price;
    };

    Pizza.prototype.getExtraIngredients = function () {
    return extrasPrice;
    };

    Pizza.prototype.getPizzaInfo = function () {
    return
    Size: ${_size.size}, type: ${
    type.type
    }; extra ingredients: ${extrasType}; price: ${
    _size.price + this.type.price
    }UAH;
    };
    }

    /* Sizes, types and extra ingredients */
    Pizza.SIZE_S = { size: 'SMALL', price: 50 };
    Pizza.SIZE_M = { size: 'MEDIUM', price: 75 };
    Pizza.SIZE_L = { size: 'LARGE', price: 100 };

    Pizza.TYPE_VEGGIE = { type: 'VEGGIE', price: 50 };
    Pizza.TYPE_MARGHERITA = { type: 'MARGHERITA', price: 60 };
    Pizza.TYPE_PEPPERONI = { type: 'PEPPERONI', price: 70 };

    Pizza.EXTRA_TOMATOES = { extra: 'TOMATOES', price: 5 };
    Pizza.EXTRA_CHEESE = { extra: 'CHEESE', price: 7 };
    Pizza.EXTRA_MEAT = { extra: 'MEAT', price: 9 };

    /* Allowed properties */
    Pizza.allowedSizes = [Pizza.SIZE_S, Pizza.SIZE_M, Pizza.SIZE_L];
    Pizza.allowedTypes = [Pizza.TYPE_VEGGIE, Pizza.TYPE_MARGHERITA, Pizza.TYPE_PEPPERONI];
    Pizza.allowedExtraIngredients = [Pizza.EXTRA_TOMATOES, Pizza.EXTRA_CHEESE, Pizza.EXTRA_MEAT];

    function PizzaException(log) {
    this.log = log;
    PizzaException.prototype.log = function () {
    return log;
    };
    }

    //////////////// Tests //////////////////
    // // small pizza, type Margherita 110 UAH
    // let pizza = new Pizza(Pizza.SIZE_S, Pizza.TYPE_MARGHERITA);
    // // add extra meat 110 + 9 = 119
    // pizza.addExtraIngredient(Pizza.EXTRA_MEAT);
    // console.log(
    Price: ${pizza.getPrice()} UAH); //Price: 119 UAH
    // // add extra cheese 119 + 7 = 126
    // pizza.addExtraIngredient(Pizza.EXTRA_CHEESE);
    // // add extra tomatoes 126 + 5 = 131;
    // pizza.addExtraIngredient(Pizza.EXTRA_TOMATOES);
    // console.log(
    Price with extra ingredients: ${pizza.getPrice()} UAH); // Price: 131 UAH
    // // check pizza size
    // console.log(
    Is pizza large: ${pizza.getSize() === Pizza.SIZE_L}); //Is pizza large: false
    // // remove extra ingredient cheese 131 - 7 = 124
    // pizza.removeExtraIngredient(Pizza.EXTRA_CHEESE);
    // console.log(
    Extra ingredients: ${pizza.getExtraIngredients().length}); // Extra ingredients: 2
    // console.log(pizza.getPizzaInfo()); //Size: SMALL, type: MARGHERITA; extra ingredients: MEAT,TOMATOES; price: 124UAH.

    //////////// Examples of errors ///////////////////////
    /////////////////////////// 1 ///////////////////////
    // let pizza = new Pizza(Pizza.SIZE_S); // "Required two arguments, given: 1"

    /////////////////////////// 2 ///////////////////////
    // let pizza = new Pizza(Pizza.SIZE_S, Pizza.SIZE_S); // "Invalid type"

    /////////////////////////// 3 ///////////////////////
    // let pizza = new Pizza(Pizza.SIZE_S, Pizza.TYPE_PEPPERONI);
    // pizza.addExtraIngredient(Pizza.EXTRA_MEAT);
    // pizza.addExtraIngredient(Pizza.EXTRA_MEAT); // "Duplicate ingredient"

    /////////////////////////// 4 ///////////////////////
    // let pizza = new Pizza(Pizza.SIZE_S, Pizza.TYPE_VEGGIE);
    // pizza.addExtraIngredient(Pizza.EXTRA_MEAT); // "Invalid ingredient"

    /////////////////////////// 5 ///////////////////////
    // let pizza = new Pizza(Pizza.SIZE_S, Pizza.TYPE_VEGGIE);
    // pizza.addExtraIngredient(Pizza.EXTRA_CORN); // "Invalid ingredient"<i>
    </i>
    ``
    ×

    Success!

    Help @Larisa spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.4,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...