1 | var filename = process.argv[2] || './format.js'
|
---|
2 | , format = require(filename)
|
---|
3 | , printf = format.printf
|
---|
4 | ;
|
---|
5 |
|
---|
6 | function desc(x, indentLevel) {
|
---|
7 | indentLevel = indentLevel || 0;
|
---|
8 | var indent = new Array(indentLevel).join(' ');
|
---|
9 | if (typeof x == 'string' || (x && x.__proto__ == String.prototype)) {
|
---|
10 | return indent + '"' + x + '"';
|
---|
11 | }
|
---|
12 | else if (Array.isArray(x)) {
|
---|
13 | return indent + '[ ' + x.map(desc).join(', ') + ' ]';
|
---|
14 | }
|
---|
15 | else {
|
---|
16 | return '' + x;
|
---|
17 | }
|
---|
18 | }
|
---|
19 |
|
---|
20 | function assertFormat(args, expected) {
|
---|
21 | var fmt = args[0];
|
---|
22 | var result = format.format.apply(format, args);
|
---|
23 | if (result !== expected) {
|
---|
24 | console.log('FORMAT: "' + fmt + '"');
|
---|
25 | console.log('ARGS: ' + desc(args.slice(1)));
|
---|
26 | console.log('RESULT: "' + result + '"');
|
---|
27 | throw new Error('assertion failed, ' + result + ' !== ' + expected);
|
---|
28 | }
|
---|
29 | }
|
---|
30 |
|
---|
31 | console.log('Testing format:');
|
---|
32 |
|
---|
33 | var tests = [
|
---|
34 | [['hello'], 'hello'],
|
---|
35 | [['hello %s', 'sami'], 'hello sami'],
|
---|
36 | [
|
---|
37 | ['b: %b\nc: %c\nd: %d\nf: %f\no: %o\ns: %s\nx: %x\nX: %X', 42, 65, 42*42, 42*42*42/1000000000, 255, 'sami', 0xfeedface, 0xc0ffee],
|
---|
38 | "b: 101010\nc: A\nd: 1764\nf: 0.000074\no: 0377\ns: sami\nx: 0xfeedface\nX: 0xC0FFEE"
|
---|
39 | ],
|
---|
40 | [['%.2f', 3.14159], '3.14'],
|
---|
41 | [['%0.2f', 3.14159], '3.14'],
|
---|
42 | [['%.2f', 0.1234], '.12'],
|
---|
43 | [['%0.2f', 0.1234], '0.12'],
|
---|
44 | [['foo %j', 42], 'foo 42'],
|
---|
45 | [['foo %j', '42'], 'foo "42"']
|
---|
46 | ];
|
---|
47 | tests.forEach(function(spec) {
|
---|
48 | var args = spec[0];
|
---|
49 | var expected = spec[1];
|
---|
50 | assertFormat(args, expected);
|
---|
51 | console.log('pass (format ' + args[0] + ' == ' + expected + ')');
|
---|
52 | });
|
---|
53 |
|
---|
54 | console.log('all passed');
|
---|