Skip to content
This repository has been archived by the owner on Dec 1, 2017. It is now read-only.

Commit

Permalink
Replacing util.format with compat.format to fix Issue#3 and have node…
Browse files Browse the repository at this point in the history
… < 5.4 compatibility
  • Loading branch information
ozten committed Feb 12, 2012
1 parent c4f2840 commit 6b946af
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 2 deletions.
24 changes: 24 additions & 0 deletions lib/compat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//var format = require('util').format;

/**
* Weak version of util.format supports only %s placeholders.
* Fixes Issue#3 compatibility with node < 5.4
*/
exports.format = function (fmt, args) {
if (fmt.indexOf('%d') != -1 ||
fmt.indexOf('%j') != -1) {
throw "This format only supports %s placeholders";
}
if (typeof arguments[0] != 'string') {
throw "First argument to format, must be a format string";
}
var i = 0;
var params = arguments;
return fmt.replace(/%s/g, function () {
i++;
if (params[i] === undefined) {
throw "Number of arguments didn't match format placeholders.";
}
return params[i];
});
}
2 changes: 1 addition & 1 deletion lib/connect-cachify.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */

var crypto = require('crypto'),
format = require('util').format,
format = require('./compat').format,
fs = require('fs'),
path = require('path'),
und = require('underscore');
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"name": "connect-cachify",
"description": "Connect middleware to provide easy frontend caching.",
"keywords": ["cache", "HTTP", "expires", "asset", "max-age", "caching"],
"version": "0.0.2",
"version": "0.0.3",
"homepage": "http://github.com/mozilla/connect-cachify",
"repository": {
"type": "git",
Expand Down
26 changes: 26 additions & 0 deletions test/compat-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
var compat = require('../lib/compat'),
format = compat.format,
nodeunit = require('nodeunit');

exports.format = nodeunit.testCase({
"typical format": function (test) {
test.equal(format("/%s%s", "foo", "/bar"), "/foo/bar");
test.equal(format("%s/%s", "foo", "bar"), "foo/bar");
test.equal(format("%s", "foo"), "foo");
test.equal(format("ID#%s", 32432), "ID#32432");
test.equal(format("foo"), "foo");
test.done();
},
"programmer error": function (test) {
test.throws(function () {
format(1, "foo", "/bar");
});
test.throws(function () {
format("%d/%d", 1, 2);
});
test.throws(function () {
format("%s/%s");
});
test.done();
}
});

0 comments on commit 6b946af

Please sign in to comment.