Skip to content

Commit

Permalink
Implements LRU cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Feb 29, 2016
1 parent 1b4b0e1 commit d8a761b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
20 changes: 18 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,20 @@ var applySourceMap = require('vinyl-sourcemaps-apply');
var objectAssign = require('object-assign');
var replaceExt = require('replace-ext');
var babel = require('babel-core');
var lru = require('lru-cache');
var crypto = require('crypto');

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

module.exports = function (opts) {
module.exports = function (opts, lruOptions) {
opts = opts || {};

lruOptions = lruOptions || 500;

var cache = lru(lruOptions);

return through.obj(function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
Expand All @@ -34,7 +40,17 @@ module.exports = function (opts) {
sourceMapTarget: file.relative
});

var res = babel.transform(file.contents.toString(), fileOpts);
var resultHash = crypto.createHash('sha1').update(file.contents.toString()).digest('hex');

var res;

res = cache.get(resultHash);

if (!res) {
res = babel.transform(file.contents.toString(), fileOpts);

cache.set(resultHash, res);
}

if (file.sourceMap && res.map) {
res.map.file = replaceExtension(res.map.file);
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"dependencies": {
"babel-core": "^6.0.2",
"gulp-util": "^3.0.0",
"lru-cache": "^4.0.0",
"object-assign": "^4.0.1",
"replace-ext": "0.0.1",
"through2": "^2.0.0",
Expand Down
8 changes: 5 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,15 @@ gulp.task('default', () =>

## API

### babel([options])
### babel([babelOptions][, lruCacheOptions = 500])

#### options
#### babelOptions

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

#### lruCacheOptions

See [`lru-cache` options](https://github.com/isaacs/node-lru-cache#options).

## Source Maps

Expand All @@ -59,7 +62,6 @@ gulp.task('default', () =>
);
```


## Babel Metadata

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

0 comments on commit d8a761b

Please sign in to comment.