Edit:. For simplicity and in order to try to make this question and sample code more general, I left the detail. An important detail is that in the light of one of the answers (which was wonderful). This system will be used primarily to display things in a date range. Low / high numbers in code often represent Unix timestamps, which can span weeks or months. Edit end
I have a page where I provide a representation of data objects that have properties that fall within a specific range. Since the user interacts with the idea of ββhis change, he is usually a sequential range change (0-9, 10-19 ...). I retrieve this data from the server, and as I understand it, it caches it so that a subsequent request for data in this range is already available. Each time I read the data, I first check if I have cache data, and if not, I read it from the server and set up the cache.
A crude, oversimplified example:
var cache, haveCache, read; cache = { rangeLow: 0, rangeHigh: 10, data: [ //whatever has been read so far between current low and high { low: 1, high: 3, // ...other props }, { low: 5, high: 6, // ...other props }, //... ] }; haveCache = function( low, high ) { return ! ( low < cache.rangeLow || high > cache.rangeHigh ); }; read = function( low, high ) { var data; if( ! haveCache( low, high ) ) { //go to outside source and read in info , then merge to cache // // when merging to cache: // if `low` param is lower than `cache.rangeLow`, overwrite cache.rangeLow with `low` // if `high` param is higher than `cache.rangeHigh`, overwrite `cache.rangeHigh` with `high` } //read data from cache return data; };
This works fine as long as the change in range is really consistent. However, I realized that there is a way to change the view not sequentially and skip a large set of values. So, let's say I am now showing ranges 10-19, and I have cache memory for ranges 0-29. The user then requests data for the range 60-69. The way it works at the moment, I will ask the server to provide data and return it and present it in order. But now, the Low and rangeHigh cache ranges from 0 to 69, while it actually only stores data for ranges 0-29 and 60-69. Items with properties from 30 to 59 are not in the cache and will never be restored.
What (best, effective) mechanism or algorithm can be used to store cached information and determine if the current displayed range is in the cache?
Thanks a lot jim