Advertisement
xapu

JS Advanced - 26 October 2019

Feb 13th, 2020
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Task 1
  2. function solve() {
  3.     let priceSoFar = 0;
  4.  
  5.     let itemInputs = document.querySelectorAll('#add-new input');
  6.     let addButton = document.querySelector('#add-new button');
  7.     let avaliableProductsList = document.querySelector('#products ul')
  8.     let myProductsList = document.querySelector('#myProducts ul');
  9.     let filterInput = document.querySelector('#filter')
  10.     let filterTrigger = document.querySelector('.filter button')
  11.  
  12.     let totalPriceRef = document.querySelectorAll('h1');
  13.  
  14.     let buyButton = document.querySelector('#myProducts button')
  15.  
  16.     buyButton.addEventListener('click', buyHandler)
  17.     avaliableProductsList.addEventListener('click', addProductToBasketHandler)
  18.     addButton.addEventListener('click', addItemHandler)
  19.     filterTrigger.addEventListener('click', filterItems)
  20.  
  21.     function buyHandler() {
  22.         myProductsList.innerHTML = '';
  23.         totalPriceRef[1].innerHTML = 'Total Price: 0.00'
  24.         priceSoFar = 0;
  25.     }
  26.  
  27.     function addProductToBasketHandler(e) {
  28.         if (e.target.tagName === 'BUTTON') {
  29.  
  30.  
  31.             let productPrice = e.target.parentNode.querySelector('strong').textContent;
  32.             let productName = e.target.parentNode.parentNode.querySelector('span').textContent;
  33.             let basketElement = document.createElement('li')
  34.             basketElement.innerText = productName;
  35.  
  36.             let productQuantityCountRef = e.target.parentNode.parentNode.querySelector('strong');
  37.             let parsedQuantity = Number(productQuantityCountRef.innerHTML.split(':')[1].trim())
  38.             productQuantityCountRef.innerHTML = `Available: ${parsedQuantity - 1}`
  39.  
  40.             if (parsedQuantity - 1 === 0) {
  41.                 e.target.parentNode.parentNode.remove()
  42.             }
  43.  
  44.             let basketElementProductPrice = document.createElement('strong')
  45.             basketElementProductPrice.innerText = productPrice;
  46.             basketElement.appendChild(basketElementProductPrice)
  47.             myProductsList.appendChild(basketElement);
  48.             priceSoFar += Number(productPrice);
  49.             totalPriceRef[1].innerHTML = `Total Price: ${(priceSoFar).toFixed(2)}`
  50.         }
  51.     }
  52.  
  53.     function filterItems() {
  54.         let filterValue = filterInput.value;
  55.         Array.from(avaliableProductsList.children).forEach(el => {
  56.             let productName = el.querySelector('span')
  57.             if (productName.innerText.toLowerCase().includes(filterValue.toLowerCase())) {
  58.                 el.style.display = 'block'
  59.             } else {
  60.                 el.style.display = 'none'
  61.             }
  62.         })
  63.     }
  64.  
  65.     function addItemHandler(e) {
  66.  
  67.         e.preventDefault()
  68.  
  69.         let newItemLine = document.createElement('li');
  70.  
  71.         let itemName = document.createElement('span');
  72.         itemName.innerText = itemInputs[0].value;
  73.  
  74.         let itemQuantity = document.createElement('strong');
  75.         itemQuantity.innerText = `Available: ${itemInputs[1].value}`;
  76.  
  77.         newItemLine.appendChild(itemName);
  78.         newItemLine.appendChild(itemQuantity);
  79.  
  80.         let priceContainer = document.createElement('div');
  81.  
  82.         let priceElement = document.createElement('strong');
  83.         priceElement.innerText = Number(itemInputs[2].value).toFixed(2);
  84.  
  85.         let addButton = document.createElement('button');
  86.         addButton.innerText = `Add to Client's List`;
  87.  
  88.  
  89.        priceContainer.appendChild(priceElement);
  90.        priceContainer.appendChild(addButton);
  91.        newItemLine.appendChild(priceContainer);
  92.  
  93.        avaliableProductsList.appendChild(newItemLine);
  94.        avaliableProductsList.innerHTML
  95.  
  96.        itemInputs[0].value = '';
  97.        itemInputs[1].value = '';
  98.        itemInputs[2].value = '';
  99.    }
  100. }
  101.  
  102. // task 2
  103.  
  104. describe('SkiResort', function () {
  105.    let skiResort;
  106.    // rN === Resort name
  107.    let rN = 'Resort Name'
  108.    beforeEach(function () {
  109.        skiResort = new SkiResort(rN)
  110.    })
  111.  
  112.    let stringifyCompare = (a, b) => assert.deepEqual(JSON.stringify(a), JSON.stringify(b))
  113.  
  114.    describe('Instantiation with one parameter ', function () {
  115.        it('When created with string should have name , empty hotels and voters', function () {
  116.            assert.deepEqual(skiResort.name, rN);
  117.            assert.deepEqual(skiResort.voters, 0);
  118.            stringifyCompare(skiResort.hotels, []);
  119.        })
  120.    })
  121.  
  122.    describe('bestHotel method', function () {
  123.        it('no voters case', function () {
  124.            assert.deepEqual(skiResort.bestHotel, 'No votes yet');
  125.        }),
  126.            it('voters case', function () {
  127.  
  128.                skiResort.build('Name', 10)
  129.                skiResort.leave('Name', 10, 10)
  130.                skiResort.build('Name2', 10)
  131.                skiResort.leave('Name2', 10, 20)
  132.                // TODO Retrun here after we find out what this method does
  133.                // let best = skiResort.hotels.reduce((a, b) => a.points > b.points ? a : b);
  134.                assert.deepEqual(skiResort.bestHotel, `Best hotel is Name2 with grade 200. Available beds: 20`)
  135.            })
  136.    })
  137.  
  138.    describe('Build hotel', function () {
  139.        it('should throw if there is no name', function () {
  140.            // assert.throws(() => { skiResort.build() });
  141.            assert.throws(() => { skiResort.build('', 2) });
  142.        })
  143.        it('should throw if the beds are less than 1 or none', function () {
  144.            assert.throws(() => { skiResort.build('', 0) });
  145.            assert.throws(() => { skiResort.build('') });
  146.        })
  147.        it('It should add a hotel to the hotel array', function () {
  148.            assert.deepEqual(skiResort.build('New Hotel', 10), `Successfully built new hotel - New Hotel`)
  149.            stringifyCompare(skiResort.hotels, [{
  150.                name: 'New Hotel',
  151.                beds: 10,
  152.                points: 0
  153.            }])
  154.        })
  155.    })
  156.  
  157.    describe('Test booking', function () {
  158.        it('Should throw error if wrong input', function () {
  159.  
  160.            assert.throws(() => { skiResort.book() })
  161.            assert.throws(() => { skiResort.book('', 1) })
  162.            assert.throws(() => { skiResort.book('Name', 0) })
  163.        })
  164.  
  165.        it('Should throw  if there is no hotel with such name', function () {
  166.            assert.throws(() => { skiResort.book('Name', 5) })
  167.        })
  168.        it('Should throw  if there is no hotel with such name', function () {
  169.            skiResort.build('Name', 10)
  170.            assert.throws(() => { skiResort.book('Name', 11) })
  171.        })
  172.        it('Should throw  if there is no hotel with such name', function () {
  173.            skiResort.build('Name', 10)
  174.            assert.deepEqual(skiResort.book('Name', 10), 'Successfully booked')
  175.        })
  176.        it('Should throw  the beds are not decremented in the hotel', function () {
  177.            skiResort.build('Name', 10)
  178.            skiResort.book('Name', 10)
  179.            stringifyCompare(skiResort.hotels, [{ name: 'Name', beds: 0, points: 0 }])
  180.        })
  181.    })
  182.  
  183.    describe('Test leave func', function () {
  184.        it('should throw with wrong params', function () {
  185.            assert.throws(() => skiResort.leave('', 10, 10))
  186.            assert.throws(() => skiResort.leave('Name', 0, 10))
  187.            assert.throws(() => skiResort.leave('Name', 20, 10))
  188.        })
  189.        it('should return success message', function () {
  190.            skiResort.build('Name', 10)
  191.            assert.deepEqual(skiResort.leave('Name', 10, 10), `10 people left Name hotel`)
  192.        })
  193.        it('should increment hotel score', function () {
  194.            skiResort.build('Name', 10)
  195.            skiResort.leave('Name', 10, 10)
  196.            stringifyCompare(skiResort.hotels, [{ name: 'Name', beds: 20, points: 100 }])
  197.        })
  198.    })
  199.  
  200.    describe('it should return the avg grade', function () {
  201.        it('should return when no voters', function () {
  202.            assert.deepEqual(skiResort.averageGrade(), 'No votes yet')
  203.        })
  204.        it('should return the average score', function () {
  205.            skiResort.build('Name', 10)
  206.            skiResort.leave('Name', 10, 10)
  207.            assert.deepEqual(skiResort.averageGrade(), `Average grade: ${(10).toFixed(2)}`)
  208.        })
  209.    })
  210. });
  211.  
  212. // task 3
  213.  
  214. class Forum {
  215.    _id = 1;
  216.    _users = [];
  217.    _questions = [];
  218.    currentLoggedUsers = []
  219.  
  220.    register(username, password, repeatPassword, email) {
  221.        if (!(username && password && repeatPassword && email)) {
  222.            throw new Error('Input can not be empty')
  223.        }
  224.  
  225.        if (password !== repeatPassword) {
  226.            throw new Error('Passwords do not match')
  227.        }
  228.  
  229.        if (this._users.find(x => x.username === username || x.email === email)) {
  230.            throw (new Error('This user already exists!'))
  231.        }
  232.        this._users.push({
  233.            username,
  234.            email,
  235.            password
  236.        })
  237.  
  238.        return `${username} with ${email} was registered successfully!`
  239.    }
  240.  
  241.    login(username, password) {
  242.        // What if the pass is wrong
  243.        if (!this._users.find(x => x.username === username && x.password === password)) {
  244.            throw new Error("There is no such user")
  245.        }
  246.        if (this._users.find(x => x.username === username && x.password === password)) {
  247.            this.currentLoggedUsers.push(username);
  248.            return "Hello! You have logged in successfully"
  249.        }
  250.  
  251.    }
  252.  
  253.    logout(username, password) {
  254.        if (!this._users.find(x => x.username === username)) {
  255.            throw new Error("There is no such user")
  256.        }
  257.        if (this._users.find(x => x.username === username && x.password === password)) {
  258.            return "You have logged out successfully"
  259.        }
  260.  
  261.        this.currentLoggedUsers = this.currentLoggedUsers.filter(x => x !== username)
  262.    }
  263.  
  264.    postQuestion(username, question) {
  265.        if (!this._users.find(x => x.username === username) || !this.currentLoggedUsers.includes(username)) {
  266.            throw new Error("You should be logged in to post questions")
  267.        }
  268.  
  269.        if (!question) {
  270.            throw new Error("Invalid question")
  271.        }
  272.  
  273.        this._questions.push({
  274.            id: this._id,
  275.            question,
  276.            postedBy: username,
  277.            answers: []
  278.        })
  279.        this._id++;
  280.        return 'Your question has been posted successfully'
  281.    }
  282.  
  283.    postAnswer(username, questionId, answer) {
  284.        if (!this._users.find(x => x.username === username) || !this.currentLoggedUsers.includes(username)) {
  285.            throw new Error("You should be logged in to post answers")
  286.        }
  287.  
  288.        if (!answer) {
  289.            throw new Error("Invalid answer")
  290.        }
  291.  
  292.        if (questionId >= this._id || questionId < 1) {
  293.            throw new Error("There is no such question")
  294.        }
  295.  
  296.        let questionRef = this._questions.find(question => question.id === questionId);
  297.        questionRef.answers.push({
  298.            answeredBy: username,
  299.            answer
  300.        })
  301.  
  302.        return 'Your answer has been posted successfully'
  303.    }
  304.  
  305.    showQuestions() {
  306.        let temp = this._questions
  307.  
  308.        // Question {id} by {username}: {question}
  309.        // ---{username}: {answer}
  310.        // Question {id} by {username}: {question}
  311.        // ---{username}: {answer}
  312.        // ---{username}: {answer}
  313.  
  314.        // ${i!==0?'\n':''}
  315.        return this._questions.reduce((acc, x, i) => {
  316.            return acc += `Question ${x.id} by ${x.postedBy}: ${x.question}`
  317.                + x.answers.reduce((answerAcc, answer) => {
  318.                    return answerAcc += `\n---${answer.answeredBy}: ${answer.answer}`
  319.                }, '') + '\n'
  320.        }, '').trim()
  321.    }
  322. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement