Skip to content

Commit

Permalink
Added some addition type-safety checks.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason LaPorte committed Jul 30, 2013
1 parent 6a11b06 commit 424e2de
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
Expand Down
8 changes: 8 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
Expand All @@ -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();
});
Expand Down

0 comments on commit 424e2de

Please sign in to comment.