Есть ли способ сжать мой код Javascript, чтобы сделать его более кратким?

#javascript #html

#javascript #HTML

Вопрос:

Я создал базовый сайт, который принимает входные данные из выпадающего списка, а также ввод текста и предоставляет результат на основе этого. Я довольно новичок в программировании и просто создаю их как личные проекты, на которых можно учиться, но я чувствую, что должен быть способ сделать этот код более сжатым? Если у кого-нибудь есть какие-либо данные, которые помогут мне улучшить, я был бы очень признателен!

Также я хотел бы знать, как сделать так, чтобы javascript принимал как Portsmouth, так и portsmouth не в верхнем регистре, например, поскольку в настоящее время он принимает его, только если он напечатан точно так, как он есть в коде.

Спасибо 🙂

 function chinesePortsmouth() {
    var chineseFood = ['The Taste Of China', 'Noble House', 'Tin Tin'];
    var chineseFood = chineseFood[Math.floor(Math.random() * chineseFood.length)];
    document.getElementById("restDisplay").innerHTML = chineseFood;
}

function chineseBrighton() {
    var chineseFood = ['China Garden', 'The Lucky Star', 'Good Friends'];
    var chineseFood = chineseFood[Math.floor(Math.random() * chineseFood.length)];
    document.getElementById("restDisplay").innerHTML = chineseFood;
}

function italianPortsmouth() {
    var italianFood = ['Bella Calabria', 'Sopranos', 'O Sole Mio Two'];
    var italianFood = italianFood[Math.floor(Math.random() * italianFood.length)];
    document.getElementById("restDisplay").innerHTML = italianFood;
}

function italianBrighton() {
    var italianFood = ['Al Duomo', 'Polpo Brighton', 'Si Signore'];
    var italianFood = italianFood[Math.floor(Math.random() * italianFood.length)];
    document.getElementById("restDisplay").innerHTML = italianFood;
}

function indianPortsmouth() {
    var indianFood = ['The Akash', 'Blue Cobra', 'Spice Merchants'];
    var indianFood = indianFood[Math.floor(Math.random() * indianFood.length)];
    document.getElementById("restDisplay").innerHTML = indianFood;
}

function indianBrighton() {
    var indianFood = ['Curry Leaf Cafe', 'Indian Summer', 'The Chilli Pickle'];
    var indianFood = indianFood[Math.floor(Math.random() * indianFood.length)];
    document.getElementById("restDisplay").innerHTML = indianFood;
}

function mexicanPortsmouth() {
    var mexicanFood = ['Chiquito', 'Bonitas', 'Las Iguanas'];
    var mexicanFood = mexicanFood[Math.floor(Math.random() * mexicanFood.length)];
    document.getElementById("restDisplay").innerHTML = mexicanFood;
}

function mexicanBrighton() {
    var mexicanFood = ['Dos Sombreros', 'Wahaca Brighton', 'Carlito Burrito'];
    var mexicanFood = mexicanFood[Math.floor(Math.random() * mexicanFood.length)];
    document.getElementById("restDisplay").innerHTML = mexicanFood;
}

function restChoice() {
    var e = document.getElementById("restaurants");
    var result = e.options[e.selectedIndex].text;
    var inputVal = document.getElementById("search").value;
    if (result == "Chinese" amp;amp; inputVal == "Portsmouth") {
        chinesePortsmouth();
    } else if (result == "Chinese" amp;amp; inputVal == "Brighton") {
        chineseBrighton();
    } else if (result == "Italian" amp;amp; inputVal == "Portsmouth") {
        italianPortsmouth();
    } else if (result == "Italian" amp;amp; inputVal == "Brighton") {
        italianBrighton();
    } else if (result == "Indian" amp;amp; inputVal == "Portsmouth") {
        indianPortsmouth();
    } else if (result == "Indian" amp;amp; inputVal == "Brighton") {
        indianBrighton();
    } else if (result == "Mexican" amp;amp; inputVal == "Portsmouth") {
        mexicanPortsmouth();
    } else if (result == "Mexican" amp;amp; inputVal == "Brighton") {
        mexicanBrighton();
    }
}

  <button onclick="restChoice()" id="button">Button</button>
    <select id="restaurants">
        <option value = "1" id="chi">Chinese</option>
        <option value = "2" id="ita">Italian</option>
        <option value = "3" id="ind">Indian</option>
        <option value = "4" id="mex">Mexican</option>
      </select>

    <input type="text" id="search">

    <div id="restDisplay"></div>
  

Ответ №1:

Хорошей практикой является проверка кода, в котором вы постоянно повторяетесь. Помните принцип DRY. Также заставляйте функции выполнять то, что им конкретно поручено, это поможет вам точно определить ошибки в будущем. Вы можете попробовать использовать объекты для группировки логики и назначения ей методов. В этом случае я использую объект для группировки выбора блюд в ресторане в массивах. Затем создал функцию для выбора блюд на основе выбранного ресторана.

 const restaurants = {
  chinesePortsmouth: ['The Taste Of China', 'Noble House', 'Tin Tin'],
  chineseBrighton: ['China Garden', 'The Lucky Star', 'Good Friends'],
  italianFood: ['Bella Calabria', 'Sopranos', 'O Sole Mio Two'],
  italianBrighton: ['Al Duomo', 'Polpo Brighton', 'Si Signore'],
  indianPortsmouth: ['The Akash', 'Blue Cobra', 'Spice Merchants'],
  indianBrighton: ['Curry Leaf Cafe', 'Indian Summer', 'The Chilli Pickle'],
  mexicanPortsmouth: ['Chiquito', 'Bonitas', 'Las Iguanas'],
  mexicanBrighton: ['Dos Sombreros', 'Wahaca Brighton', 'Carlito Burrito']
};

function pickFood (foodChoices) {
  return foodChoices[Math.floor(Math.random() * foodChoices.length)];
}

function restChoice() {
  var e = document.getElementById('restaurants');
  var inputVal = document.getElementById('search').value.toLowerCase();
  var result = e.options[e.selectedIndex].text;
  let name = null;
  
  if (result == 'Chinese' amp;amp; inputVal == 'porstmouth') {
    name = 'chinesePortsmouth';
  } else if (result == 'Chinese' amp;amp; inputVal == 'Brighton') {
    name = 'chineseBrighton';
  } else if (result == 'Italian' amp;amp; inputVal == 'porstmouth') {
    name = 'italianPortsmouth';
  } else if (result == 'Italian' amp;amp; inputVal == 'Brighton') {
    name = 'italianBrighton';
  } else if (result == 'Indian' amp;amp; inputVal == 'porstmouth') {
    name = 'indianPortsmouth';
  } else if (result == 'Indian' amp;amp; inputVal == 'Brighton') {
    name = 'indianBrighton';
  } else if (result == 'Mexican' amp;amp; inputVal == 'porstmouth') {
    name = 'mexicanPortsmouth';
  } else if (result == 'Mexican' amp;amp; inputVal == 'Brighton') {
    name = 'mexicanBrighton';
  }

  // Render food choice
  document.getElementById("restDisplay").innerHTML = pickFood(restaurants[name]);
}
  

Для принятия Portsmouth и portsmouth просто проверьте правильность написания независимо от его стиля. В этом случае сначала введите введенное значение в нижнем регистре и просто сравните его с «portsmouth».

 // Can be Portsmouth,portsmouth,PORTSMOUTH,pOrtSmouth
var inputVal = document.getElementById('search').value;

if (inputVal.toLowerCase() === 'portsmouth) {
  // Do Something
}
  

Ответ №2:

При попытке рефакторинга хороший совет — всегда думать о том, что делает каждую функцию уникальной. В этом случае единственное различие между вашими функциями заключается в массиве. Учитывая это, вы можете создать функцию, которая принимает массив, поскольку это единственный неизвестный.

 function setRestDisplay(foodItems) {
    var item = foodItems[Math.floor(Math.random() * foodItems.length)];
    document.getElementById("restDisplay").innerHTML = foodItems;
}
  

Попробуйте разобраться restChoice самостоятельно и дайте мне знать, если вы все еще застряли 🙂