/*
Оплата за проживание в отеле
// Необходимо написать функцию расчета стоимости проживания посетителя в отеле
// Функция может принимать 2 аргумента
// 1. Количество ночей проживания в отеле (обязательный параметр)
// 2. Дата заселения (необязательный параметр). Если значение не указано, то отсчет ведется от текущего дня
// Стоимость проживания в будние дни (с понедельника по пятницу) стоит 1500 руб.
// Стоимость проживания в выходные дни (суббота, воскресенье) стоит 2200 руб.
*/
// const prices = {
// weekday: 1500,
// holiday: 2200,
// };
// function bookingCalculate(days, date = new Date()) {
// const dateOfArrival = date;
// let result = 0;
// for (let i = 0; i < days; i++) {
// const dayNum = dateOfArrival.getDay();
// if (dayNum === 6 || dayNum === 0) {
// result += prices.holiday;
// } else {
// result += prices.weekday;
// }
// dateOfArrival.setDate(dateOfArrival.getDate() + 1);
// }
// return result;
// }
// console.log(bookingCalculate(7)); // 11900
// console.log(bookingCalculate(3, new Date('2023-11-10'))); // 5900
// const a = new Date('2026-04-12').getDay();
// console.log(a);
// =======================================================================
// Задача 1. Аренда велосипеда
// Напишите функцию расчета стоимости аренды велосипеда.
// Функция принимает:
// 1. Количество часов аренды (обязательный параметр)
// 2. Тип велосипеда: "обычный" или "электрический" (необязательный, по умолчанию "обычный")
// Цены:
// - Обычный велосипед: первые 3 часа по 100 руб/час, далее по 70 руб/час
// - Электрический: первые 2 часа по 250 руб/час, далее по 200 руб/час
// Если часы указаны дробные (например, 1.5 часа), округлить вверх до целого часа.
// =======================================================================
// const calculateBikeRental = (hours, type = "обычный") => {
// let result = 0;
// let finalHours = Math.ceil(hours);
// if (type === "обычный"){
// for(let i = 0; i < finalHours; i++) {
// if (i < 3) {
// result += 100;
// }
// else {
// result += 70;
// }
// }
// }
// if (type === "электрический"){
// for(let i = 0; i < finalHours; i++) {
// if (i < 2) {
// result += 250;
// }
// else {
// result += 200;
// }
// }
// }
// return result;
// };
// const calculateBikeRental = (hours, type = 'обычный') => {
// let result = 0;
// let finalHours = Math.ceil(hours);
// console.log(finalHours);
// const isRegular = type === 'обычный';
// for (let i = 0; i < finalHours; i++) {
// if (isRegular) {
// if (i < 3) {
// result += 100;
// } else {
// result += 70;
// }
// }
// if (!isRegular) {
// if (i < 2) {
// result += 250;
// } else {
// result += 200;
// }
// }
// }
// return result;
// };
// Примеры: console.log(calculateBikeRental(2.4)); // => 300
// console.log(calculateBikeRental(4, 'электрический')); // => 250*2 + 200*2 = 900
// console.log(calculateBikeRental(1.2)); // => 100*2 = 200 (округление вверх до 2 часов)2
// Задача 6. Группировка по статусу с суммой и максимальным значением
// Вернуть объект с ключами status, а значение - объект
// вида { count: количество, totalAmount: сумма, maxAmount: максимальная сумма }
// Пример:
const transactions = [
{ status: 'pending', amount: 300 },
{ status: 'completed', amount: 1200 },
{ status: 'failed', amount: 100 },
{ status: 'pending', amount: 700 },
{ status: 'completed', amount: 800 },
];
// groupByStatusWithStats(transactions);
// => {
// completed: { count: 3, totalAmount: 2500, maxAmount: 1200 },
// pending: { count: 2, totalAmount: 1000, maxAmount: 700 },
// failed: { count: 1, totalAmount: 100, maxAmount: 100 }
// }
// function groupByStatusWithStats(transactions) {
// let result = {};
// transactions.forEach(el => {
// const { amount, status } = el;
// if (!result[transactions][status]) {
// result[status] = { count: 1, totalAmount: amount, maxAmount: amount };
// } else {
// result =
// [status]: {
// count: count + 1,
// totalAmount: totalAmount + amount,
// maxAmount: maxAmount + amount,
// },
//
// }
// });
// return result;
// }
// function groupByStatusWithStats(transactions) {
// let result = {};
// for (let i=0; i < transactions.length; i++){
// for (const [key, value] of Object.entries(transactions[i])) {
// if (key === "completed") {
// }
// }
// }
// return result;
// }
// function groupByStatusWithStats(transactions) {
// let result = {};
// transactions.forEach(el => {
// const { amount, status } = el;
// // { status: 'completed', amount: 500 }, //el
// // result = {} true
// // result = {pending: {count: 1, totalAmount: 300, maxAmount: 300 }}
// // result = {peding : {...}}
// if (!result[status]) {
// result[status] = { count: 1, totalAmount: amount, maxAmount: amount };
// } else {
// const current = result[status];
// result[status] = {
// count: current.count + 1,
// totalAmount: current.totalAmount + amount,
// maxAmount: Math.max(current.maxAmount, amount),
// };
// }
// });
// return result;
// }
// console.log(groupByStatusWithStats(transactions));
// 1. Вернуть объект с ключами type из масива,
// значение - массив элементов с таким type
// 2. Вернуть объект с ключами type, а значение - объект
// вида {count: количество, weight: суммарный вес}
// const arr = [
// { type: 'banana', weight: 32 },
// { type: 'apple', weight: 24 },
// { type: 'kiwi', weight: 55 },
// { type: 'banana', weight: 44 },
// { type: 'orange', weight: 5 },
// ];
// const groupByType = arr => {
// let resObj = {};
// for (let i = 0; i < arr.length; i++) {
// if (!resObj[arr[i].type]) {
// resObj[arr[i].type] = [arr[i]]; // resObj: { banana: [{ type: 'banana', weight: 32 }] }
// } else {
// resObj[arr[i].type].push(arr[i]);
// }
// }
// return resObj;
// };
// console.log(groupByType(arr));
// Задача 7. Группировка по году с массивом названий
//
// Вернуть объект с ключами year, а значение - массив названий фильмов
// за этот год (без дубликатов, отсортированный по алфавиту)
//
// Пример:
const movies = [
{ title: 'Inception', year: 2010 },
{ title: 'The Dark Knight', year: 2008 },
{ title: 'Interstellar', year: 2014 },
{ title: 'Memento', year: 2000 },
{ title: 'Dunkirk', year: 2017 },
{ title: 'The Prestige', year: 2006 },
{ title: 'Oleg', year: 2006 },
{ title: 'Inception', year: 2010 }, // дубликат
];
// groupMoviesByYear(movies);
// => {
// 2010: ["Inception"],
// 2008: ["The Dark Knight"],
// 2014: ["Interstellar"],
// 2000: ["Memento"],
// 2017: ["Dunkirk"],
// 2006: ["The Prestige"]
// }
// function groupMoviesByYear(arr) {
// let resObj = {};
// for (let i = 0; i < arr.length; i++) {
// if (!resObj[arr[i].year]) {
// resObj[arr[i].year] = [arr[i].title];
// } else {
// resObj[arr[i].year].push(arr[i].title);
// resObj[arr[i].year].sort();
// // return [...new Set(resObj[arr[i].year]]
// }
// [... new Set(resObj[arr[i].title])]
// }
// return resObj;
// }
// function groupMoviesByYear(arr) {
// let result = {};
// for (let elem of arr) {
// const { year, title } = elem;
// if (!result[year]) {
// result[year] = [title];
// } else {
// for (let elem of result[year]) {
// if (elem !== title) {
// result[year].push(title);
// }
// }
// result[year].sort()
// }
// }
// return result;
// }
// console.log(groupMoviesByYear(movies));
// Задача 9. Группировка по категории с преобразованием в массив
//
// Сгруппировать товары по полю category.
// Внутри каждой группы создать массив объектов,
// содержащих только поля name и price (без id и category).
// Объекты в массиве отсортировать по цене (по возрастанию).
//
// Пример:
const products = [
{ id: 1, category: 'fruit', name: 'apple', price: 100 },
{ id: 2, category: 'fruit', name: 'banana', price: 80 },
{ id: 3, category: 'vegetable', name: 'carrot', price: 50 },
{ id: 4, category: 'fruit', name: 'orange', price: 120 },
{ id: 5, category: 'vegetable', name: 'potato', price: 40 },
];
// groupByCategorySorted(products);
// // => {
// // fruit: [
// // { name: "banana", price: 80 },
// // { name: "apple", price: 100 },
// // { name: "orange", price: 120 }
// // ],
// // vegetable: [
// // { name: "potato", price: 40 },
// // { name: "carrot", price: 50 }
// // ]
// // }
//=======================================================================
const groupByCategorySorted = data => {
let resObj = {};
for (let el of data) {
const { category, name, price } = el;
if (!resObj[category]) {
resObj[category] = [{ name, price }];
} else {
resObj[category].push({name , price})
resObj[category].sort((a, b) => a.price - b.price)
}
}
return resObj;
};
console.log(groupByCategorySorted(products));
Click Run to execute JavaScript.
Code runs in an isolated environment.
Code runs in an isolated environment.