Хорошо на вас за вопрос, как улучшить! Я вижу такой код слишком часто, и есть много способов его упростить.
Ваш оригинальный код
if (time >= 0 && time < 4) {
greet = 'Wow you\'re up late! Good morning.';
}
else if (time >= 4 && time < 12) {
greet = 'Good morning.';
}
else if (time >= 12 && time < 17) {
greet = 'Good afternoon.';
}
else if (time >= 17 && time <= 23) {
greet = 'Good evening.';
}
Улучшение # 1
Здесь мы несколько первых шагов и удаления избыточного кода/упростить вещи
if(time < 0) {
//dont do anything
}
// now we can take "time >= 0 && " out, making it easier to read
else if (time < 4) {
greet = 'Wow you\'re up late! Good morning.';
}
//here, we don't actually need to check if time >= 4, because if it wasn't
//it would have been dealt with by a previous condition
else if (time < 12) {
greet = 'Good morning.';
}
//and the same for the rest of them
else if (time < 17) {
greet = 'Good afternoon.';
}
//lets keep things consistant by using "time < 24" rather than "time <= 23"
else if (time < 24) {
greet = 'Good evening.';
}
Улучшение # 2
Перепроверка структурирование может упростить код еще больше, так что позволяет бросить этот код в функцию
//in this function we can take advantage of the order of operations
//to simplify further
function getGreeting(time){
//returning early when things go wrong is always a good idea
if(time < 0) {
return null;
}
//We dont need 'else' because we are returning when a condition is met,
//and the app doesn't have a chance to try the other conditionals
//the less 'else's you have the better the code IMO :)
if (time < 4) {
//return our string instead of setting it!
return 'Wow you\'re up late! Good morning.';
}
if (time < 12) {
return 'Good morning.';
}
if (time < 17) {
return 'Good afternoon.';
}
if (time < 24) {
return 'Good evening.';
}
}
//then call the function
greet = getGreeting(time);
Улучшение # 3
Мы можем сделать лучше ... со структурами данных!
function getGreeting(time){
//we still check for stuff that shouldn't happen
if(time < 0) {
return null;
}
//Here we declare a 'greetings' array. In the array there are objects!
//each object has a field for time start and end as well as a greeting
//the thing that makes this approach so neat is that adding more data in
//the future
//is dead easy, and the data can now come from a database or whatever
//you want.
var greetings = [
{
timeStart: 0,
timeEnd: 4,
greeting: 'Wow you\'re up late! Good morning.'
},
{
timeStart: 4,
timeEnd: 12,
greeting: 'Good morning.'
},
{
timeStart: 12,
timeEnd: 17,
greeting: 'Good afternoon.'
},
{
timeStart: 17,
timeEnd: 24,
greeting: 'Good evening.'
}
];
//We can add as many new items to the greetings array without ever
// touching this again!
for(var i = 0; i < greetings.length; i++)
{
if(time >= greetings[i].timeStart && time < greetings[i].timeEnd)
{
return greetings[i].greeting;
}
}
}
//then call the function
greet = getGreeting(time);
Мне это нравится (ES6) тоже! – trincot
Это именно тот тип ответа, на который я надеялся, он достаточно читабельный, он современный, он аккуратный и аккуратный. Я буду использовать это решение и polyfill 'findIndex' для тех бедных душ в IE11 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex – matt3224
@ matt3224, вы можете делать то, что тебе нравится. ИМО, это жертвует удобочитаемостью, ремонтопригодностью, совместимостью между браузерами и, возможно, скоростью для «отличной». Теперь, если вы инкапсулировали это так, что это было фактически ООП, или, по крайней мере, использовали один объект с свойствами «startTime» и «message», а не двумя отдельными (глобальными) массивами (которые не имеют неотъемлемых отношений), это могут иметь некоторые функции погашения. Для того, чтобы делать то, что вы на самом деле делаете, это плохой выбор. [Это не плохой пример того, что можно сделать, это просто нехороший выбор того, что нужно сделать.] – Makyen