Memoizing previously queried data for charts rendering

This is a common scenario: suppose you need to write a function to display bar/pie charts for some data infographics  through remote REST API call.

Like click a button to display a bar chart, but you only need to query once; after first time AJAX call, it is not necessary to call the remote API anymore when user click on the button again or query the same chart again. Say you have  parameters and id to query a static REST data, it is a good practice to allow the function to memoize the previous queried data. How ?

Use function property.

function displayChart(para,id){
   if(display[para+id]){//already queried
   }else{
     display[para+id] = query(para,id);
   } 
   render(display[para+id]);
}
function query(para,id){
  $.ajax({})//return the data
}
function render(data){
  //display the chart according to the data
}

From an idea to store distinct data on array:
 var store = {
   parking: [],
   cache: {},
   add: function(item) {
      if ( !this.cache[item]) { 
          this.cache[item]= 1;
          this.parking.push(item);
      }
  }
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s