From 5f1b99e10e0219f52d6a8dd1ccf979b4c3e7b38a Mon Sep 17 00:00:00 2001 From: Neeraj Poddar Date: Tue, 6 Dec 2016 16:43:51 -0600 Subject: [PATCH] Added an option to throw an error on no matching substitutions. Added an options argument to exported function which can enable the functionality of throwing an error if template pattern doesn't match any of the passed argument strings. Default behavior is as before i.e. no matching substitutions are replaced with empty strings. --- index.js | 15 ++++++++++++--- test/string-template.js | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) 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() +})