How to create local cache for dynamic search results

by shlomo hassid

HTML

Search&nbsp;<input name="search" />
<br /><br />Results Found in: <span id="loaded" style="color:red"></span><br />
<ul id="search-results" style="border:1px solid black">
</ul>

JavaScript

//this is the variable that will store the ajax call
var request = null;
// create object
var cache = {
  storageFIFO: [], // The array that will hold our results 
  maxResults: 20, // max enteries in the storedResultFifo array - will shift once when exceeded
  pushResults: function(phrase, data) {
    cache.storageFIFO.push({
      term: phrase,
      data: data
    });
    if (cache.storageFIFO.length > cache.maxResults) {
      cache.storageFIFO.shift();
    }
  },
  getCachedResults: function(phrase) {
    //First try exact match against cached search terms:
    for (var i = 0; i < cache.storageFIFO.length; i++)
      if (cache.storageFIFO[i].term === phrase)
        return cache.storageFIFO[i].data;
    //try phrase as a substring of the terms stored in the cache
    for (var i = 0; i < cache.storageFIFO.length; i++)
      if (cache.storageFIFO[i].term.includes(phrase))
        return cache.storageFIFO[i].data;
    return false;
  }
};
//Called with data to draw mon the screen:
var drawResults = function(data, loadedFrom, empty = true) {
  //erase older results if requested:
  if (empty) $('#search-results').html("");
  //Loaded from indicator:
  $('#loaded').text(loadedFrom);
  //Loop through the results and add the to the container:
  $.each(data, function(key, value) {
    if (value != null && value.constructor.name === "Array") return; //avoid empty non object
    $('#search-results').append(
      '<li><a href="' + value.href + '">' + value.name + '</a></li>'
    );
  });
  console.log(cache);
};
//Bind the event to search:
$('input[name="search"]').on('keyup', function() {
  var phrase = jQuery.trim($(this).val());
  if (phrase.length <= 1) return;
  //This is just for testing and generating random data:
  var randomData = [];
  for (var i = 0; i < Math.floor(Math.random() * (20 - 5 + 1)) + 5; i++)
    randomData.push({
      phrase: phrase,
      href: "#",
      name: phrase + "_" + Math.random().toString(36).substring(7)
    });
  //This will...