From 6a11b0677b15ed20d966fa6996c94f2a09e6e412 Mon Sep 17 00:00:00 2001 From: Jason LaPorte Date: Tue, 30 Jul 2013 13:35:01 -0400 Subject: [PATCH] A bit more cleanup. --- TODO | 6 ++---- lib/template.js | 20 ++++++++++++++++---- test.js | 11 ++++++++++- 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/TODO b/TODO index 228cd2e8..c1499bbc 100644 --- a/TODO +++ b/TODO @@ -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() { diff --git a/lib/template.js b/lib/template.js index 2e7479a0..0d590921 100644 --- a/lib/template.js +++ b/lib/template.js @@ -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) && diff --git a/test.js b/test.js index fc842f7d..48fec5f3 100644 --- a/test.js +++ b/test.js @@ -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() { @@ -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() {