Last active
July 30, 2021 10:33
-
-
Save chizhovdee/5d6e45dd917b196cdc7e950c9785cbaa to your computer and use it in GitHub Desktop.
hotel stay cost
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Дано: день пребывания в отеле в рабочий день стоит 1000р, а в выходной 1500р. Задача: написать код который посчитает стоимость за пребывание в течении X дней с указанной даты | |
*/ | |
const weekdayPrice = 1000; | |
const weekendsPrice = 1500; | |
// version 1 | |
const stayCost1 = (daysAmount, startDate = new Date()) => { | |
const currentDay = startDate.getDay(); | |
const weekDays = new Array(daysAmount) | |
.fill(currentDay) | |
.map((day, index) => (index + day) % 7 || 7); | |
return weekDays.reduce((sum, day) => sum + (day > 5 ? weekendsPrice : weekdayPrice), 0) | |
} | |
// version 2 | |
const stayCost2 = (daysAmount, startDate = new Date()) => { | |
const currentDay = startDate.getDay(); | |
return new Array(daysAmount) | |
.fill(0) | |
.map((i, j) => i + j) | |
.reduce((sum, dayIndex) => { | |
const day = (dayIndex + currentDay) % 7 || 7; | |
return sum + (day > 5 ? weekendsPrice : weekdayPrice); | |
}, 0) | |
} | |
// version 3 | |
const PRICE_STANDARD = 1000 | |
const PRICE_WEEKEND = 1500 | |
function datePrice(date) { | |
return isWeekend(date) ? PRICE_WEEKEND : PRICE_STANDARD | |
} | |
function isWeekend(date) { | |
const dayOfWeek = date.getDay(); | |
const dayOfWeekSaturday = 6; | |
const dayOfWeekSunday = 0; | |
return [dayOfWeekSaturday, dayOfWeekSunday].includes(dayOfWeek); | |
} | |
function bill(startDate, nights) { | |
let sum = 0; | |
for(let n = 0; n < nights; n++){ | |
let date = new Date(); | |
date.setDate(startDate.getDate() + n); | |
sum = sum + datePrice(date); | |
} | |
return sum; | |
} | |
console.log(bill(new Date(2021, 7, 30), 1)) // 1000 | |
console.log(bill(new Date(2021, 7, 31), 1)) // 1500 | |
console.log(bill(new Date(2021, 7, 25), 7)) // 8000 | |
console.log(bill(new Date(2021, 7, 26), 6)) // 6500 | |
console.log(bill(new Date(2021, 7, 27), 5)) // 5500 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment