Skip to content

Commit

Permalink
A bit more cleanup.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason LaPorte committed Jul 30, 2013
1 parent 6001d4c commit 6a11b06
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
6 changes: 2 additions & 4 deletions TODO
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
- We should allow leaf nodes of the template tree to be zero-argument
functions.
- We should allow some way of passing variables or data down the tree.

Doing both of the above would allow us, at least in English, to remove the
hacky prefix-stripping we currently do on days of the week and let us pass a
Doing the above would allow us, at least in English, to remove the hacky
prefix-stripping we currently do on days of the week and let us pass a
"use_preposition" flag to them:

"morning": function() {
Expand Down
20 changes: 16 additions & 4 deletions lib/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,24 @@ module.exports = function(template) {
if(!template.hasOwnProperty(expr))
throw new Error("\"" + expr + "\" not found in language template.");

else if(typeof template[expr] !== "string" ||
/\$\d+/.test(template[expr]))
throw new Error("\"" + expr + "\" was used in a value context, but is expected in a template context.");
else if(typeof template[expr] === "string") {
if(/\$\d+/.test(template[expr]))
throw new Error("\"" + expr + "\" was used in a value context, but is expected in a template context.");

else
return template[expr];
}

else if(typeof template[expr] === "function") {
if(template[expr].length !== 0)
throw new Error("\"" + expr + "\" was used in a value context, but is expected in a template context.");

else
return template[expr]();
}

else
return template[expr];
throw new Error("\"" + expr + "\" is not a valid language template pattern.");
}

else if(Array.isArray(expr) &&
Expand Down
11 changes: 10 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ describe("translation", function() {
var convert = template({
"foo": "bar",
"bar": "meeple $2",
"baz": function(a, b) { return "meeple " + b; }
"baz": function(a, b) { return "meeple " + b; },
"quux": function() { return "glorple"; }
});

it("should return a number in string form", function() {
Expand Down Expand Up @@ -62,6 +63,14 @@ describe("translation", function() {
it("should throw an error given an object", function() {
expect(function() { convert({}); }).to.throw();
});

it("should apply an expected value conversion given a zero-argument function", function() {
expect(convert("quux")).to.equal("glorple");
});

it("should fail to apply a function template given a value", function() {
expect(function() { convert("baz"); }).to.throw();
});
});

describe("language", function() {
Expand Down

0 comments on commit 6a11b06

Please sign in to comment.