I'm having a problem figuring out how I can make this particular part of my code DRY. Currently, the code is repeating itself but with minor changes in each case of a switch.
SearchParam is a string that the user has searched for in the application that this code is from. The function creates a new li element with searchParam as the text. This value is then added to localStorage as 'search1'. Dependent on how many li elements there are already, the function uses a switch to add the new li element to the beginning of the list. If there are already 3 items, then the last item in the list will be deleted and removed.
function searchHistory(searchParam) {
var liElements = $('#history').children();
var recentSearch = liElements.first();
var newItem = `
<li>
<i class="fa fa-long-arrow-right icons"></i>
<p class="list-title">${searchParam}</p>
</li>
`;
switch($('#history').children().length) {
case 0:
$('#history').append(newItem);
localStorage.setItem('search1', searchParam);
break;
case 1:
var secondSearch = liElements.children()[1].innerHTML;
recentSearch.before(newItem);
localStorage.setItem('search1', searchParam);
localStorage.setItem('search2', secondSearch);
break;
case 2:
var secondSearch = liElements.children()[1].innerHTML;
var thirdSearch = liElements.children()[3].innerHTML;
recentSearch.before(newItem);
localStorage.setItem('search1', searchParam);
localStorage.setItem('search2', secondSearch);
localStorage.setItem('search3', thirdSearch);
break;
default:
var oldSearch = liElements.last();
var secondSearch = liElements.children()[1].innerHTML;
var thirdSearch = liElements.children()[3].innerHTML;
localStorage.setItem('search1', searchParam);
localStorage.setItem('search2', secondSearch);
localStorage.setItem('search3', thirdSearch);
recentSearch.before(newItem);
oldSearch.remove();
}
};