Skip to content

Commit d8a761b

Browse files
committed
Implements LRU cache.
1 parent 1b4b0e1 commit d8a761b

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

index.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,20 @@ var applySourceMap = require('vinyl-sourcemaps-apply');
66
var objectAssign = require('object-assign');
77
var replaceExt = require('replace-ext');
88
var babel = require('babel-core');
9+
var lru = require('lru-cache');
10+
var crypto = require('crypto');
911

1012
function replaceExtension(fp) {
1113
return path.extname(fp) ? replaceExt(fp, '.js') : fp;
1214
}
1315

14-
module.exports = function (opts) {
16+
module.exports = function (opts, lruOptions) {
1517
opts = opts || {};
1618

19+
lruOptions = lruOptions || 500;
20+
21+
var cache = lru(lruOptions);
22+
1723
return through.obj(function (file, enc, cb) {
1824
if (file.isNull()) {
1925
cb(null, file);
@@ -34,7 +40,17 @@ module.exports = function (opts) {
3440
sourceMapTarget: file.relative
3541
});
3642

37-
var res = babel.transform(file.contents.toString(), fileOpts);
43+
var resultHash = crypto.createHash('sha1').update(file.contents.toString()).digest('hex');
44+
45+
var res;
46+
47+
res = cache.get(resultHash);
48+
49+
if (!res) {
50+
res = babel.transform(file.contents.toString(), fileOpts);
51+
52+
cache.set(resultHash, res);
53+
}
3854

3955
if (file.sourceMap && res.map) {
4056
res.map.file = replaceExtension(res.map.file);

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
"dependencies": {
3737
"babel-core": "^6.0.2",
3838
"gulp-util": "^3.0.0",
39+
"lru-cache": "^4.0.0",
3940
"object-assign": "^4.0.1",
4041
"replace-ext": "0.0.1",
4142
"through2": "^2.0.0",

readme.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,15 @@ gulp.task('default', () =>
3030

3131
## API
3232

33-
### babel([options])
33+
### babel([babelOptions][, lruCacheOptions = 500])
3434

35-
#### options
35+
#### babelOptions
3636

3737
See the Babel [options](https://babeljs.io/docs/usage/options/), except for `sourceMap` and `filename` which is handled for you.
3838

39+
#### lruCacheOptions
40+
41+
See [`lru-cache` options](https://github.com/isaacs/node-lru-cache#options).
3942

4043
## Source Maps
4144

@@ -59,7 +62,6 @@ gulp.task('default', () =>
5962
);
6063
```
6164

62-
6365
## Babel Metadata
6466

6567
Files in the stream are annotated with a `babel` property, which contains the metadata from [`babel.transform()`](https://babeljs.io/docs/usage/api/).

0 commit comments

Comments
 (0)