diff --git a/index.js b/index.js index 52945bb..2d6b7e8 100644 --- a/index.js +++ b/index.js @@ -4,9 +4,14 @@ module.exports = template function template(string) { var args + var opts if (arguments.length === 2 && typeof arguments[1] === "object") { args = arguments[1] + } else if (arguments.length === 3 && typeof arguments[1] === "object" && + typeof arguments[2] === "object") { + args = arguments[1] + opts = arguments[2] } else { args = new Array(arguments.length - 1) for (var i = 1; i < arguments.length; ++i) { @@ -25,9 +30,13 @@ function template(string) { string[index + match.length] === "}") { return i } else { - result = args.hasOwnProperty(i) ? args[i] : null - if (result === null || result === undefined) { - return "" + if (opts && opts.rejectNoMatch && !args.hasOwnProperty(i)) { + throw new Error('No matching substitution available for the pattern'); + } else { + result = args.hasOwnProperty(i) ? args[i] : null + if (result === null || result === undefined) { + return "" + } } return result diff --git a/test/string-template.js b/test/string-template.js index e279bbd..c634aee 100644 --- a/test/string-template.js +++ b/test/string-template.js @@ -225,3 +225,21 @@ test("Template string with underscores", function (assert) { assert.equal(result, "Hello James Bond, how are you?") assert.end() }) + +test("Reject no matching substitution", function (assert) { + assert.throws(function() { + format("I am {name}. I am {age} years old", + {name: "Anna"}, {rejectNoMatch: true}) + }) + assert.end() +}) + +test("Allow no matching substitution", function (assert) { + var result + assert.doesNotThrow(function() { + result = format("I am {name}. I am {age} years old", + {name: "Anna"}, {rejectNoMatch: false}) + }) + assert.equal(result, "I am Anna. I am years old"); + assert.end() +})