diff --git a/lib/template.js b/lib/template.js index 0d590921..76be0dbe 100644 --- a/lib/template.js +++ b/lib/template.js @@ -38,10 +38,18 @@ module.exports = function(template) { return parse(expr[n.slice(1)|0]); }); - else if(typeof template[expr[0]] === "function") - return template[expr[0]].apply(null, expr.slice(1).map(function(arg) { - return parse(arg); - })); + else if(typeof template[expr[0]] === "function") { + if(template[expr[0]].length === 0) + throw new Error("\"" + expr[0] + "\" was used in a template context, but is expected in a value context."); + + else if(template[expr[0]].length !== expr.length - 1) + throw new Error("Template \"" + expr[0] + "\" did not expect " + (expr.length - 1) + " arguments."); + + else + return template[expr[0]].apply(null, expr.slice(1).map(function(arg) { + return parse(arg); + })); + } else throw new Error("\"" + expr[0] + "\" is not a valid language template pattern."); diff --git a/test.js b/test.js index 48fec5f3..2cf5e90f 100644 --- a/test.js +++ b/test.js @@ -42,6 +42,10 @@ describe("translation", function() { expect(convert(["bar", 10, 20])).to.equal("meeple 20"); }); + it("should fail to apply a function template given the wrong number of arguments", function() { + expect(function() { convert(["baz", 10, 20, 30]); }).to.throw(); + }); + it("should apply a function template", function() { expect(convert(["baz", 10, 20])).to.equal("meeple 20"); }); @@ -68,6 +72,10 @@ describe("translation", function() { expect(convert("quux")).to.equal("glorple"); }); + it("should fail to apply a zero-argument function given arguments", function() { + expect(function() { convert(["quux"]); }).to.throw(); + }); + it("should fail to apply a function template given a value", function() { expect(function() { convert("baz"); }).to.throw(); });