Skip to content

Commit

Permalink
Add LRU caching, and test
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs committed Dec 22, 2011
1 parent 89230ee commit f8a6f88
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
16 changes: 15 additions & 1 deletion minimatch.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
module.exports = minimatch
minimatch.Minimatch = Minimatch

var LRU = require("lru-cache")
, cache = minimatch.cache = new LRU(100)

var path = require("path")
// any single thing other than /
// don't need to escape / when using new RegExp()
Expand Down Expand Up @@ -77,11 +80,22 @@ function Minimatch (pattern, options) {
}

if (!options) options = {}
pattern = pattern.trim()

// lru storage.
// these things aren't particularly big, but walking down the string
// and turning it into a regexp can get pretty costly.
var cacheKey = pattern + "\n" + Object.keys(options).filter(function (k) {
return options[k]
}).join(":")
var cached = minimatch.cache.get(cacheKey)
if (cached) return cached
minimatch.cache.set(cacheKey, this)

this.options = options
this.set = []
this.regExpSet = []
this.pattern = pattern.trim()
this.pattern = pattern
this.regexp = null
this.negate = false
this.comment = false
Expand Down
14 changes: 14 additions & 0 deletions test/caching.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
var Minimatch = require("../minimatch.js").Minimatch
var tap = require("tap")
tap.test("cache test", function (t) {
var mm1 = new Minimatch("a?b")
var mm2 = new Minimatch("a?b")
t.equal(mm1, mm2, "should get the same object")
// the lru should drop it after 100 entries
for (var i = 0; i < 100; i ++) {
new Minimatch("a"+i)
}
mm2 = new Minimatch("a?b")
t.notEqual(mm1, mm2, "cache should have dropped")
t.end()
})

0 comments on commit f8a6f88

Please sign in to comment.