Skip to content

Commit

Permalink
Allow LRU cache to gracefully handle cases where the same key is adde…
Browse files Browse the repository at this point in the history
…d twice

fixes #2201
  • Loading branch information
Lucas Wojciechowski committed Mar 1, 2016
1 parent 4058e8d commit 90baedf
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
2 changes: 1 addition & 1 deletion debug/site.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ var map = new mapboxgl.Map({
container: 'map',
zoom: 12.5,
center: [-77.01866, 38.888],
style: 'mapbox://styles/mapbox/streets-v8',
style: 'mapbox://styles/mapbox/satellite-hybrid-v8',
hash: true
});

Expand Down
18 changes: 13 additions & 5 deletions js/util/lru_cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,20 @@ LRUCache.prototype.reset = function() {
* @private
*/
LRUCache.prototype.add = function(key, data) {
this.data[key] = data;
this.order.push(key);

if (this.order.length > this.max) {
var removedData = this.get(this.order[0]);
if (removedData) this.onRemove(removedData);
if (this.has(key)) {
this.order.splice(this.order.indexOf(key), 1);
this.data[key] = data;
this.order.push(key);

} else {
this.data[key] = data;
this.order.push(key);

if (this.order.length > this.max) {
var removedData = this.get(this.order[0]);
if (removedData) this.onRemove(removedData);
}
}

return this;
Expand Down
18 changes: 16 additions & 2 deletions test/js/util/lru_cache.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,27 @@ test('LRUCache', function(t) {
t.end();
});

test('LRUCache - duplicate add', function(t) {
var cache = new LRUCache(10, function() {
t.fail();
});

cache.add('a', 'b');
cache.add('a', 'c');

t.deepEqual(cache.keys(), ['a']);
t.ok(cache.has('a'));
t.equal(cache.get('a'), 'c');
t.end();
});

test('LRUCache - overflow', function(t) {
var cache = new LRUCache(1, function(removed) {
t.equal(removed, 'c');
t.equal(removed, 'b');
t.end();
});
cache.add('a', 'b');
cache.add('a', 'c');
cache.add('c', 'd');
});

test('LRUCache#reset', function(t) {
Expand Down

0 comments on commit 90baedf

Please sign in to comment.