Permalink
Browse files

Making a better String.format method

  • Loading branch information...
bbyars committed May 29, 2011
1 parent 851f19f commit adc820a11bf0734d4defcbe878f71d32315e2f36
Showing with 26 additions and 0 deletions.
  1. +11 −0 server/lib/extensions.js
  2. +15 −0 server/test/unit/extensions.test.js
View
@@ -10,3 +10,14 @@ String.prototype.format = function () {
return formatted;
};
+String.prototype.interpolate = function (replacements) {
+ return this.replace(/\{(\w+)\}/g, function (match, capture) {
+ if (replacements[capture]) {
+ return replacements[capture];
+ }
+ else {
+ return match;
+ }
+ });
+};
+
@@ -13,6 +13,21 @@ exports.String = testCase({
'format should replace placeholders': function (test) {
test.strictEqual('test {0} {1}'.format('one', 'two'), 'test one two');
test.done();
+ },
+
+ 'interpolate should return string if no placeholders': function (test) {
+ test.strictEqual('test'.interpolate({ key: 'value' }), 'test');
+ test.done();
+ },
+
+ 'interpolate should replace placeholders': function (test) {
+ test.strictEqual('{one} {two}'.interpolate({ one: 1, two: 2 }), '1 2');
+ test.done();
+ },
+
+ 'interpolate should not replace placeholders lacking a replacement': function (test) {
+ test.strictEqual('{one} {two}'.interpolate({ one: 1 }), '1 {two}');
+ test.done();
}
});

0 comments on commit adc820a

Please sign in to comment.