//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...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!