Permalink
Browse files

Add `it.` to make it run more than 30 times faster

  • Loading branch information...
1 parent 2103adb commit 48f78b548c6e210172065ec162cd16698fb1df98 @shaunlee committed Apr 28, 2011
Showing with 27 additions and 15 deletions.
  1. +1 −0 .gitignore
  2. +4 −0 Readme.md
  3. +22 −15 lib/jst.js
View
@@ -1,3 +1,4 @@
*~
*.swp
+test/*
View
@@ -36,6 +36,10 @@ via npm:
var fn = jst.compile('Hello {{ name }}');
fn({name: 'jst'});
+ // Turn on `useIt` so that you can run it more than 30 times faster
+ jst.configure({useIt: true});
+ jst.render('Hello {{ it.name }}', {name: 'jst'});
+
## License
(The MIT License)
View
@@ -10,33 +10,40 @@ var fs = require('fs'),
exports.version = '0.0.1';
var _cache = {},
- _files = {};
+ _files = {},
+ _options = {
+ useIt: false
+ };
function md5sum(ctx) {
return crypto.createHash('md5').update(ctx).digest('hex');
}
-var compile = exports.compile = function(ctx) {
- var ck = md5sum(ctx);
+exports.configure = function(options) {
+ for (var prop in options)
+ _options[prop] = options[prop];
+}
- if (typeof _cache[ck] === 'undefined') {
- var code = 'var out = ""; with(args) { out += "'
+var compile = exports.compile = function(ctx) {
+ var code = (_options.useIt ? 'var out = "' : 'var out = ""; with(it) { out += "')
+ ctx.replace(/[\t\r\n]/g, '')
.replace(/"/g, '\\"').replace(/\{#.+?#\}/g, '')
.replace(/\{\{ (.*?) \}\}/g, '"; out += $1; out +="')
.split('\{% ').join('"; ')
.split(' %\}').join(' out +="')
- + '"; } return out;';
- _cache[ck] = new Function('args', code);
- }
-
- return function(args) {
- return _cache[ck](args);
- };
+ + (_options.useIt ? '"; return out;' : '"; } return out;');
+ return new Function('it', code);
}
var render = exports.render = function(ctx, args) {
- return compile(ctx)(args);
+ var ck = md5sum(ctx),
+ fn = _cache[ck];
+
+ if (typeof fn === 'undefined') {
+ fn = _cache[ck] = compile(ctx);
+ }
+
+ return fn(args);
}
var renderFile = exports.renderFile = function(filename, args, fn) {
@@ -62,12 +69,12 @@ var renderFile = exports.renderFile = function(filename, args, fn) {
_files[fk].ctx = ctx;
try {
- fn(null, compile(ctx)(args));
+ fn(null, render(ctx, args));
} catch(e) { fn(e); }
});
} else {
try {
- fn(null, compile(_files[fk].ctx)(args));
+ fn(null, render(_files[fk].ctx, args));
} catch(e) { fn(e); }
}
});

0 comments on commit 48f78b5

Please sign in to comment.