Skip to content
This repository has been archived by the owner on Jun 4, 2023. It is now read-only.

Commit

Permalink
lib: use some memoization for branding templating
Browse files Browse the repository at this point in the history
This allievates the use of `glob.sync()`.
  • Loading branch information
vincentbernat committed Aug 8, 2015
1 parent 4850ad1 commit 9198695
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ module.exports = function(base, substitutions) {
var onlyFor = _.map(glob.sync(path.resolve(base, '*.html')),
function(p) { return path.relative(base, p); });
onlyFor = onlyFor.concat(_.map(onlyFor, function(p) { return p.slice(0, p.length - 5); }));
var cache = {};

return function(req, res, next) {
// Handle only GET/HEAD files
if ((req.method !== 'GET' && req.method !== 'HEAD') ||
(onlyFor || []).indexOf(req.path.slice(1)) === -1) {
req.path.slice(1) in (onlyFor || []) === -1) {
return next();
}
var write = res.write;
Expand All @@ -27,6 +28,10 @@ module.exports = function(base, substitutions) {
_.each(substitutions, function(value, key) {
var regex = new RegExp('"([^"]*)\\.\\.' + key.toUpperCase() + '\\.\\.([^"]*)"(\\s*)', "g");
html = html.replace(regex, function(match, p1, p2, spaces) {
if (match in cache) {
// Do some memoization because we use glob.sync
return cache[match];
}
var file = [p1, value, p2].join('');
/* Is that really a file? We just check if we have a '/' */
if (file.indexOf('/') !== -1) {
Expand All @@ -38,9 +43,9 @@ module.exports = function(base, substitutions) {
file = path.relative(base, matches[0]);
}
}
return ['"', file, '"',
new Array(spaces.length - file.length +
p1.length + p2.length + key.length + 4 + 1).join(' ')].join('');
return (cache[match] = ['"', file, '"',
new Array(spaces.length - file.length +
p1.length + p2.length + key.length + 4 + 1).join(' ')].join(''));
});
});
return write.call(res, new Buffer(html, encoding), encoding);
Expand Down

0 comments on commit 9198695

Please sign in to comment.