Skip to content

Instantly share code, notes, and snippets.

@xjamundx
Created February 19, 2011 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xjamundx/835438 to your computer and use it in GitHub Desktop.
Save xjamundx/835438 to your computer and use it in GitHub Desktop.
This was a commonJS module we played around with for node.
////
// Math Support
//
// This is an an awesome addition to mustache.js to
// add support for basic math operations. No evals!
//
// Examples:
//
// 2 == {{#math}} {{four}} / {{two}} {{/math}}
// 20 == {{#math}} 100 / 5 {{/math}}
// 200 == {{#math}} 100 * {{two}} {{/math}}
// 603 == {{#math}} 3 + 100 * {{two}} * 3 {{/math}}
// 406 == {{#math}} {{two}} + {{two}} * {{two}} + {{two}} * 100 * {{two}} {{/math}}
////
var mathRegex = /\s*(\d+)\s*(\*|\/|\-|\+)\s*(\d+)\s*/;
var mulDivRegex = /\s*(\d+)\s*(\*|\/)\s*(\d+)\s*/;
var addSubRegex = /\s*(\d+)\s*(\-|\+)\s*(\d+)\s*/;
var applyMath = (function() {
var operands = {
"+": function(a,b){ return a+b; },
"-": function(a,b){ return a-b; },
"*": function(a,b){ return a*b; },
"/": function(a,b){ return a/b; }
}
return function(str, digit1, operand, digit2, offset, s) {
return operands[operand](parseInt(digit1, 10), parseInt(digit2, 10));
}
})();
exports.math = function math() {
return function(text, render) {
var eq = render(text);
while (eq.match(mulDivRegex) !== null) {
eq = eq.replace(mulDivRegex, applyMath);
}
while (eq.match(addSubRegex) !== null) {
eq = eq.replace(addSubRegex, applyMath);
}
return eq;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment