Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Task 1
- function solve() {
- let priceSoFar = 0;
- let itemInputs = document.querySelectorAll('#add-new input');
- let addButton = document.querySelector('#add-new button');
- let avaliableProductsList = document.querySelector('#products ul')
- let myProductsList = document.querySelector('#myProducts ul');
- let filterInput = document.querySelector('#filter')
- let filterTrigger = document.querySelector('.filter button')
- let totalPriceRef = document.querySelectorAll('h1');
- let buyButton = document.querySelector('#myProducts button')
- buyButton.addEventListener('click', buyHandler)
- avaliableProductsList.addEventListener('click', addProductToBasketHandler)
- addButton.addEventListener('click', addItemHandler)
- filterTrigger.addEventListener('click', filterItems)
- function buyHandler() {
- myProductsList.innerHTML = '';
- totalPriceRef[1].innerHTML = 'Total Price: 0.00'
- priceSoFar = 0;
- }
- function addProductToBasketHandler(e) {
- if (e.target.tagName === 'BUTTON') {
- let productPrice = e.target.parentNode.querySelector('strong').textContent;
- let productName = e.target.parentNode.parentNode.querySelector('span').textContent;
- let basketElement = document.createElement('li')
- basketElement.innerText = productName;
- let productQuantityCountRef = e.target.parentNode.parentNode.querySelector('strong');
- let parsedQuantity = Number(productQuantityCountRef.innerHTML.split(':')[1].trim())
- productQuantityCountRef.innerHTML = `Available: ${parsedQuantity - 1}`
- if (parsedQuantity - 1 === 0) {
- e.target.parentNode.parentNode.remove()
- }
- let basketElementProductPrice = document.createElement('strong')
- basketElementProductPrice.innerText = productPrice;
- basketElement.appendChild(basketElementProductPrice)
- myProductsList.appendChild(basketElement);
- priceSoFar += Number(productPrice);
- totalPriceRef[1].innerHTML = `Total Price: ${(priceSoFar).toFixed(2)}`
- }
- }
- function filterItems() {
- let filterValue = filterInput.value;
- Array.from(avaliableProductsList.children).forEach(el => {
- let productName = el.querySelector('span')
- if (productName.innerText.toLowerCase().includes(filterValue.toLowerCase())) {
- el.style.display = 'block'
- } else {
- el.style.display = 'none'
- }
- })
- }
- function addItemHandler(e) {
- e.preventDefault()
- let newItemLine = document.createElement('li');
- let itemName = document.createElement('span');
- itemName.innerText = itemInputs[0].value;
- let itemQuantity = document.createElement('strong');
- itemQuantity.innerText = `Available: ${itemInputs[1].value}`;
- newItemLine.appendChild(itemName);
- newItemLine.appendChild(itemQuantity);
- let priceContainer = document.createElement('div');
- let priceElement = document.createElement('strong');
- priceElement.innerText = Number(itemInputs[2].value).toFixed(2);
- let addButton = document.createElement('button');
- addButton.innerText = `Add to Client's List`;
- priceContainer.appendChild(priceElement);
- priceContainer.appendChild(addButton);
- newItemLine.appendChild(priceContainer);
- avaliableProductsList.appendChild(newItemLine);
- avaliableProductsList.innerHTML
- itemInputs[0].value = '';
- itemInputs[1].value = '';
- itemInputs[2].value = '';
- }
- }
- // task 2
- describe('SkiResort', function () {
- let skiResort;
- // rN === Resort name
- let rN = 'Resort Name'
- beforeEach(function () {
- skiResort = new SkiResort(rN)
- })
- let stringifyCompare = (a, b) => assert.deepEqual(JSON.stringify(a), JSON.stringify(b))
- describe('Instantiation with one parameter ', function () {
- it('When created with string should have name , empty hotels and voters', function () {
- assert.deepEqual(skiResort.name, rN);
- assert.deepEqual(skiResort.voters, 0);
- stringifyCompare(skiResort.hotels, []);
- })
- })
- describe('bestHotel method', function () {
- it('no voters case', function () {
- assert.deepEqual(skiResort.bestHotel, 'No votes yet');
- }),
- it('voters case', function () {
- skiResort.build('Name', 10)
- skiResort.leave('Name', 10, 10)
- skiResort.build('Name2', 10)
- skiResort.leave('Name2', 10, 20)
- // TODO Retrun here after we find out what this method does
- // let best = skiResort.hotels.reduce((a, b) => a.points > b.points ? a : b);
- assert.deepEqual(skiResort.bestHotel, `Best hotel is Name2 with grade 200. Available beds: 20`)
- })
- })
- describe('Build hotel', function () {
- it('should throw if there is no name', function () {
- // assert.throws(() => { skiResort.build() });
- assert.throws(() => { skiResort.build('', 2) });
- })
- it('should throw if the beds are less than 1 or none', function () {
- assert.throws(() => { skiResort.build('', 0) });
- assert.throws(() => { skiResort.build('') });
- })
- it('It should add a hotel to the hotel array', function () {
- assert.deepEqual(skiResort.build('New Hotel', 10), `Successfully built new hotel - New Hotel`)
- stringifyCompare(skiResort.hotels, [{
- name: 'New Hotel',
- beds: 10,
- points: 0
- }])
- })
- })
- describe('Test booking', function () {
- it('Should throw error if wrong input', function () {
- assert.throws(() => { skiResort.book() })
- assert.throws(() => { skiResort.book('', 1) })
- assert.throws(() => { skiResort.book('Name', 0) })
- })
- it('Should throw if there is no hotel with such name', function () {
- assert.throws(() => { skiResort.book('Name', 5) })
- })
- it('Should throw if there is no hotel with such name', function () {
- skiResort.build('Name', 10)
- assert.throws(() => { skiResort.book('Name', 11) })
- })
- it('Should throw if there is no hotel with such name', function () {
- skiResort.build('Name', 10)
- assert.deepEqual(skiResort.book('Name', 10), 'Successfully booked')
- })
- it('Should throw the beds are not decremented in the hotel', function () {
- skiResort.build('Name', 10)
- skiResort.book('Name', 10)
- stringifyCompare(skiResort.hotels, [{ name: 'Name', beds: 0, points: 0 }])
- })
- })
- describe('Test leave func', function () {
- it('should throw with wrong params', function () {
- assert.throws(() => skiResort.leave('', 10, 10))
- assert.throws(() => skiResort.leave('Name', 0, 10))
- assert.throws(() => skiResort.leave('Name', 20, 10))
- })
- it('should return success message', function () {
- skiResort.build('Name', 10)
- assert.deepEqual(skiResort.leave('Name', 10, 10), `10 people left Name hotel`)
- })
- it('should increment hotel score', function () {
- skiResort.build('Name', 10)
- skiResort.leave('Name', 10, 10)
- stringifyCompare(skiResort.hotels, [{ name: 'Name', beds: 20, points: 100 }])
- })
- })
- describe('it should return the avg grade', function () {
- it('should return when no voters', function () {
- assert.deepEqual(skiResort.averageGrade(), 'No votes yet')
- })
- it('should return the average score', function () {
- skiResort.build('Name', 10)
- skiResort.leave('Name', 10, 10)
- assert.deepEqual(skiResort.averageGrade(), `Average grade: ${(10).toFixed(2)}`)
- })
- })
- });
- // task 3
- class Forum {
- _id = 1;
- _users = [];
- _questions = [];
- currentLoggedUsers = []
- register(username, password, repeatPassword, email) {
- if (!(username && password && repeatPassword && email)) {
- throw new Error('Input can not be empty')
- }
- if (password !== repeatPassword) {
- throw new Error('Passwords do not match')
- }
- if (this._users.find(x => x.username === username || x.email === email)) {
- throw (new Error('This user already exists!'))
- }
- this._users.push({
- username,
- email,
- password
- })
- return `${username} with ${email} was registered successfully!`
- }
- login(username, password) {
- // What if the pass is wrong
- if (!this._users.find(x => x.username === username && x.password === password)) {
- throw new Error("There is no such user")
- }
- if (this._users.find(x => x.username === username && x.password === password)) {
- this.currentLoggedUsers.push(username);
- return "Hello! You have logged in successfully"
- }
- }
- logout(username, password) {
- if (!this._users.find(x => x.username === username)) {
- throw new Error("There is no such user")
- }
- if (this._users.find(x => x.username === username && x.password === password)) {
- return "You have logged out successfully"
- }
- this.currentLoggedUsers = this.currentLoggedUsers.filter(x => x !== username)
- }
- postQuestion(username, question) {
- if (!this._users.find(x => x.username === username) || !this.currentLoggedUsers.includes(username)) {
- throw new Error("You should be logged in to post questions")
- }
- if (!question) {
- throw new Error("Invalid question")
- }
- this._questions.push({
- id: this._id,
- question,
- postedBy: username,
- answers: []
- })
- this._id++;
- return 'Your question has been posted successfully'
- }
- postAnswer(username, questionId, answer) {
- if (!this._users.find(x => x.username === username) || !this.currentLoggedUsers.includes(username)) {
- throw new Error("You should be logged in to post answers")
- }
- if (!answer) {
- throw new Error("Invalid answer")
- }
- if (questionId >= this._id || questionId < 1) {
- throw new Error("There is no such question")
- }
- let questionRef = this._questions.find(question => question.id === questionId);
- questionRef.answers.push({
- answeredBy: username,
- answer
- })
- return 'Your answer has been posted successfully'
- }
- showQuestions() {
- let temp = this._questions
- // Question {id} by {username}: {question}
- // ---{username}: {answer}
- // Question {id} by {username}: {question}
- // ---{username}: {answer}
- // ---{username}: {answer}
- // ${i!==0?'\n':''}
- return this._questions.reduce((acc, x, i) => {
- return acc += `Question ${x.id} by ${x.postedBy}: ${x.question}`
- + x.answers.reduce((answerAcc, answer) => {
- return answerAcc += `\n---${answer.answeredBy}: ${answer.answer}`
- }, '') + '\n'
- }, '').trim()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement