Skip to content

Commit

Permalink
Added the ability clear items using wildcard characters
Browse files Browse the repository at this point in the history
  • Loading branch information
mikevalstar committed Apr 6, 2016
1 parent df0a9a8 commit 624708c
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 4 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ Bypass the get function and store an object directly into the cache.

### clear = function(key)

Clear a cached item, if no key is set all items will be cleared
Clear a cached item, if no key is set all items will be cleared. Returns true if an item was cleared.

_You may also clear cache items using a wildcard characters e.g. Medusa.clear('sample*')_

### settings = function(newSettings)

Expand Down
36 changes: 36 additions & 0 deletions __tests__/clearMany.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
jest.unmock('../index');
import Medusa from '../index';

describe('Clear many from storage', () => {

pit('gets the results of a promise', () => {

return Medusa.get('sample1', function(resolve, reject) {
resolve('success');
}, 1000)
.then(res => expect(res).toEqual('success'))
.then(res => {
return Medusa.get('sample2', function(resolve, reject) {
resolve('success');
}, 1000)
.then(res => expect(res).toEqual('success'));
})
.then(res => {
return Medusa.clear('samp*');
})
.then(res => {
return Medusa.get('sample1', function(resolve, reject) {
resolve('failure');
}, 1000)
.then(res => expect(res).toEqual('failure'));
})
.then(res => {
return Medusa.get('sample2', function(resolve, reject) {
resolve('failure');
}, 1000)
.then(res => expect(res).toEqual('failure'));
});

});

});
24 changes: 21 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,22 +78,40 @@ var Medusa = (function() {
if (!key) {
for (var i in cache) {
if (hOP.call(cache, i)) {
clearTimeout(cache[i].to);
delete cache[i];
md._clear(i);
}
}
return;
return true;
}

// Clear a wildcard search of objects
if (key.indexOf('*') > -1) {
var cacheMatchKeys = Object.keys(cache).filter((str) => {
return new RegExp('^' + key.split('*').join('.*') + '$').test(str);
});
cacheMatchKeys.forEach(md._clear);
// Incase someone somehow used a wildcard in their cached key (don't do this)
return cacheMatchKeys.length > 0 || md._clear(key);
}

// Not a special clear
return md._clear(key);

},

// Internal clear to bypass extra checking of the key
_clear(key) {
// Clear a single item, making sure to remove the extra timeout
if (hOP.call(cache, key)) {
if (cache[key].to) {
clearTimeout(cache[key].to);
}

delete cache[key];
return true;
}

return false;
},

};
Expand Down

0 comments on commit 624708c

Please sign in to comment.