mirror of
https://github.com/samsonjs/format.git
synced 2026-03-25 08:45:53 +00:00
Compare commits
20 commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0094c51372 | |||
| 91b6bd78af | |||
| 80570f29f9 | |||
| 72662d55dd | |||
| 93c6cf623e | |||
| 4f89809675 | |||
|
|
a2f2c59869 | ||
| 35d4cf5f4f | |||
| 7f14e8bb68 | |||
|
|
c9f6afa190 | ||
|
|
a581ee703f | ||
|
|
820d0b8608 | ||
|
|
56e0dbddc2 | ||
|
|
92cb00c5b7 | ||
|
|
5e05fc2925 | ||
|
|
1bc06f0f15 | ||
|
|
9fe2d57865 | ||
|
|
4a0f6413bb | ||
|
|
2aee1a0905 | ||
|
|
cd9f4c9eca |
11 changed files with 232 additions and 130 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
*.tmproj
|
||||
18
LICENSE
18
LICENSE
|
|
@ -1,18 +0,0 @@
|
|||
Copyright 2010 Sami Samhuri. All rights reserved.
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to
|
||||
deal in the Software without restriction, including without limitation the
|
||||
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
IN THE SOFTWARE.
|
||||
9
License.md
Normal file
9
License.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright © 2010-2016 Sami Samhuri, https://samhuri.net <sami@samhuri.net>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
13
Makefile
Normal file
13
Makefile
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
minify: real-minify test-minified
|
||||
|
||||
real-minify: format.js
|
||||
rm -f format-min.js
|
||||
closure <format.js >|format-min.js
|
||||
|
||||
test:
|
||||
node test_format.js
|
||||
|
||||
test-minified:
|
||||
node test_format.js ./format-min.js
|
||||
|
||||
.PHONY: test test-minified
|
||||
27
Readme.md
27
Readme.md
|
|
@ -3,6 +3,7 @@ format
|
|||
|
||||
printf, sprintf, and vsprintf for JavaScript
|
||||
|
||||
[](https://www.npmjs.com/package/format) [](https://www.npmjs.com/package/format) [](https://sjs.mit-license.org)
|
||||
|
||||
Installation
|
||||
============
|
||||
|
|
@ -15,9 +16,11 @@ or otherwise include them with your other JavaScript.
|
|||
Usage
|
||||
=====
|
||||
|
||||
var Format = require('format')
|
||||
, printf = Format.printf
|
||||
, format = Format.format // aliased as sprintf as well
|
||||
var format = require('format')
|
||||
, printf = format.printf
|
||||
, vsprintf = format.vsprintf
|
||||
// or if you want to keep it old school
|
||||
, sprintf = format
|
||||
|
||||
// Print 'hello world'
|
||||
printf('%s world', 'hello')
|
||||
|
|
@ -26,14 +29,24 @@ Usage
|
|||
format('%d is the answer to %s', 42, what)
|
||||
// => '42 is the answer to life, the universe, and everything'
|
||||
|
||||
Supported format specifiers: b, c, d, f, o, s, x, and X.
|
||||
vsprintf('%d is the answer to %s', [42, what])
|
||||
// => '42 is the answer to life, the universe, and everything'
|
||||
|
||||
See `man 3 printf` or `man 1 printf` for details.
|
||||
// you can format values as JSON with %j
|
||||
var value = {answer: 42}
|
||||
format('%j', value)
|
||||
// => '{"answer":42}'
|
||||
|
||||
Supported format specifiers: b, c, d, f, j, o, s, x, and X.
|
||||
|
||||
See `man 3 printf` or `man 1 printf` for details. `j` is an extension that formats values as JSON.
|
||||
|
||||
Precision is supported for floating point numbers.
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
Copyright 2010 - 2011 Sami Samhuri sami@samhuri.net
|
||||
Copyright 2010 - 2016 Sami Samhuri sami@samhuri.net
|
||||
|
||||
[MIT license](http://sjs.mit-license.org)
|
||||
|
||||
ISC (see included [LICENSE](/samsonjs/format/blob/master/LICENSE))
|
||||
|
|
|
|||
9
component.json
Normal file
9
component.json
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"name": "format",
|
||||
"repo": "samsonjs/format",
|
||||
"description": "printf, sprintf, and vsprintf for JavaScript",
|
||||
"keywords": ["format", "printf", "sprintf", "vsprintf", "string"],
|
||||
"version": "0.2.2",
|
||||
"main": "format.js",
|
||||
"scripts": ["format.js"]
|
||||
}
|
||||
2
format-min.js
vendored
Normal file
2
format-min.js
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
(function(){function f(){console.log(e.apply(null,arguments))}function e(h){for(var e=1,d=[].slice.call(arguments),g=0,f=h.length,a="",b,i=!1,j,c=function(){return d[e++]},k=function(){for(var a="";h[g].match(/\d/);)a+=h[g++];return a.length>0?parseInt(a):null};g<f;++g)if(b=h[g],i)switch(i=!1,j=k(),b){case "b":a+=parseInt(c(),10).toString(2);break;case "c":b=c();a+=typeof b==="string"||b instanceof String?b:String.fromCharCode(parseInt(b,10));break;case "d":a+=parseInt(c(),10);break;case "f":a+=parseFloat(c()).toFixed(j||
|
||||
6);break;case "o":a+="0"+parseInt(c(),10).toString(8);break;case "s":a+=c();break;case "x":a+="0x"+parseInt(c(),10).toString(16);break;case "X":a+="0x"+parseInt(c(),10).toString(16).toUpperCase();break;default:a+=b}else b==="%"?i=!0:a+=b;return a}var d;d=typeof module!=="undefined"?module.exports=e:function(){return this||(0,eval)("this")}();d.format=e;d.vsprintf=function(d,f){return e.apply(null,[d].concat(f))};if(typeof console!=="undefined"&&typeof console.log==="function")d.printf=f})();
|
||||
128
format.js
Normal file
128
format.js
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
//
|
||||
// format - printf-like string formatting for JavaScript
|
||||
// github.com/samsonjs/format
|
||||
// @_sjs
|
||||
//
|
||||
// Copyright 2010 - 2013 Sami Samhuri <sami@samhuri.net>
|
||||
//
|
||||
// MIT License
|
||||
// http://sjs.mit-license.org
|
||||
//
|
||||
|
||||
;(function() {
|
||||
|
||||
//// Export the API
|
||||
var namespace;
|
||||
|
||||
// CommonJS / Node module
|
||||
if (typeof module !== 'undefined') {
|
||||
namespace = module.exports = format;
|
||||
}
|
||||
|
||||
// Browsers and other environments
|
||||
else {
|
||||
// Get the global object. Works in ES3, ES5, and ES5 strict mode.
|
||||
namespace = (function(){ return this || (1,eval)('this') }());
|
||||
}
|
||||
|
||||
namespace.format = format;
|
||||
namespace.vsprintf = vsprintf;
|
||||
|
||||
if (typeof console !== 'undefined' && typeof console.log === 'function') {
|
||||
namespace.printf = printf;
|
||||
}
|
||||
|
||||
function printf(/* ... */) {
|
||||
console.log(format.apply(null, arguments));
|
||||
}
|
||||
|
||||
function vsprintf(fmt, replacements) {
|
||||
return format.apply(null, [fmt].concat(replacements));
|
||||
}
|
||||
|
||||
function format(fmt) {
|
||||
var argIndex = 1 // skip initial format argument
|
||||
, args = [].slice.call(arguments)
|
||||
, i = 0
|
||||
, n = fmt.length
|
||||
, result = ''
|
||||
, c
|
||||
, escaped = false
|
||||
, arg
|
||||
, tmp
|
||||
, leadingZero = false
|
||||
, precision
|
||||
, nextArg = function() { return args[argIndex++]; }
|
||||
, slurpNumber = function() {
|
||||
var digits = '';
|
||||
while (/\d/.test(fmt[i])) {
|
||||
digits += fmt[i++];
|
||||
c = fmt[i];
|
||||
}
|
||||
return digits.length > 0 ? parseInt(digits) : null;
|
||||
}
|
||||
;
|
||||
for (; i < n; ++i) {
|
||||
c = fmt[i];
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
if (c == '.') {
|
||||
leadingZero = false;
|
||||
c = fmt[++i];
|
||||
}
|
||||
else if (c == '0' && fmt[i + 1] == '.') {
|
||||
leadingZero = true;
|
||||
i += 2;
|
||||
c = fmt[i];
|
||||
}
|
||||
else {
|
||||
leadingZero = true;
|
||||
}
|
||||
precision = slurpNumber();
|
||||
switch (c) {
|
||||
case 'b': // number in binary
|
||||
result += parseInt(nextArg(), 10).toString(2);
|
||||
break;
|
||||
case 'c': // character
|
||||
arg = nextArg();
|
||||
if (typeof arg === 'string' || arg instanceof String)
|
||||
result += arg;
|
||||
else
|
||||
result += String.fromCharCode(parseInt(arg, 10));
|
||||
break;
|
||||
case 'd': // number in decimal
|
||||
result += parseInt(nextArg(), 10);
|
||||
break;
|
||||
case 'f': // floating point number
|
||||
tmp = String(parseFloat(nextArg()).toFixed(precision || 6));
|
||||
result += leadingZero ? tmp : tmp.replace(/^0/, '');
|
||||
break;
|
||||
case 'j': // JSON
|
||||
result += JSON.stringify(nextArg());
|
||||
break;
|
||||
case 'o': // number in octal
|
||||
result += '0' + parseInt(nextArg(), 10).toString(8);
|
||||
break;
|
||||
case 's': // string
|
||||
result += nextArg();
|
||||
break;
|
||||
case 'x': // lowercase hexadecimal
|
||||
result += '0x' + parseInt(nextArg(), 10).toString(16);
|
||||
break;
|
||||
case 'X': // uppercase hexadecimal
|
||||
result += '0x' + parseInt(nextArg(), 10).toString(16).toUpperCase();
|
||||
break;
|
||||
default:
|
||||
result += c;
|
||||
break;
|
||||
}
|
||||
} else if (c === '%') {
|
||||
escaped = true;
|
||||
} else {
|
||||
result += c;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}());
|
||||
82
lib/index.js
82
lib/index.js
|
|
@ -1,82 +0,0 @@
|
|||
//
|
||||
// format, printf-like string formatting for JavaScript
|
||||
// github.com/samsonjs/format
|
||||
//
|
||||
// Copyright 2010 - 2011 Sami Samhuri <sami@samhuri.net>
|
||||
// ISC license
|
||||
//
|
||||
|
||||
exports.printf = function(/* ... */) {
|
||||
console.log(exports.format.apply(this, arguments));
|
||||
};
|
||||
|
||||
exports.format = function(format) {
|
||||
var argIndex = 1 // skip initial format argument
|
||||
, args = [].slice.call(arguments)
|
||||
, i = 0
|
||||
, n = format.length
|
||||
, result = ''
|
||||
, c
|
||||
, escaped = false
|
||||
, arg
|
||||
, precision
|
||||
, nextArg = function() { return args[argIndex++]; }
|
||||
, slurpNumber = function() {
|
||||
var digits = '';
|
||||
while (format[i].match(/\d/))
|
||||
digits += format[i++];
|
||||
return digits.length > 0 ? parseInt(digits) : null;
|
||||
}
|
||||
;
|
||||
for (; i < n; ++i) {
|
||||
c = format[i];
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
precision = slurpNumber();
|
||||
switch (c) {
|
||||
case 'b': // number in binary
|
||||
result += parseInt(nextArg(), 10).toString(2);
|
||||
break;
|
||||
case 'c': // character
|
||||
arg = nextArg();
|
||||
if (typeof arg === 'string' || arg instanceof String)
|
||||
result += arg;
|
||||
else
|
||||
result += String.fromCharCode(parseInt(arg, 10));
|
||||
break;
|
||||
case 'd': // number in decimal
|
||||
result += parseInt(nextArg(), 10);
|
||||
break;
|
||||
case 'f': // floating point number
|
||||
result += parseFloat(nextArg()).toFixed(precision || 6);
|
||||
break;
|
||||
case 'o': // number in octal
|
||||
result += '0' + parseInt(nextArg(), 10).toString(8);
|
||||
break;
|
||||
case 's': // string
|
||||
result += nextArg();
|
||||
break;
|
||||
case 'x': // lowercase hexadecimal
|
||||
result += '0x' + parseInt(nextArg(), 10).toString(16);
|
||||
break;
|
||||
case 'X': // uppercase hexadecimal
|
||||
result += '0x' + parseInt(nextArg(), 10).toString(16).toUpperCase();
|
||||
break;
|
||||
default:
|
||||
result += c;
|
||||
break;
|
||||
}
|
||||
} else if (c === '%') {
|
||||
escaped = true;
|
||||
} else {
|
||||
result += c;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
exports.vsprintf = function(format, replacements) {
|
||||
return exports.format.apply(this, [format].concat(replacements));
|
||||
};
|
||||
|
||||
exports.sprintf = exports.format;
|
||||
13
package.json
13
package.json
|
|
@ -1,8 +1,8 @@
|
|||
{
|
||||
"name": "format",
|
||||
"description": "printf, sprintf, and vsprintf for JavaScript",
|
||||
"version": "0.1.4",
|
||||
"homepage": "http://samhuri.net/proj/format",
|
||||
"version": "0.2.2",
|
||||
"homepage": "https://samhuri.net/projects/format",
|
||||
"author": "Sami Samhuri <sami@samhuri.net>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
|
@ -12,19 +12,16 @@
|
|||
"email": "sami@samhuri.net",
|
||||
"url": "https://github.com/samsonjs/format/issues"
|
||||
},
|
||||
"directories": {
|
||||
"lib": "./lib"
|
||||
},
|
||||
"main": "./lib/index",
|
||||
"main": "./format.js",
|
||||
"engines": {
|
||||
"node": ">=0.4.x"
|
||||
},
|
||||
"licenses": [
|
||||
{
|
||||
"type": "MIT",
|
||||
"url": "http://github.com/samsonjs/format/raw/master/LICENSE"
|
||||
"url": "http://sjs.mit-license.org"
|
||||
}
|
||||
],
|
||||
"dependencies": {},
|
||||
"devDependencies": {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,24 +1,54 @@
|
|||
var format = require('./lib')
|
||||
var filename = process.argv[2] || './format.js'
|
||||
, format = require(filename)
|
||||
, printf = format.printf
|
||||
;
|
||||
|
||||
console.log('Testing printf:');
|
||||
printf('hello');
|
||||
console.log('(expected "hello")');
|
||||
printf('hello %s', 'sami');
|
||||
console.log('(expected "hello sami")');
|
||||
printf('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);
|
||||
console.log('(expected "b: 101010\nc: A\nd: 1764\nf: 0.000074\no: 0377\ns: sami\nx: 0xfeedface\nX: 0xC0FFEE")');
|
||||
console.log('(passed if the output looks ok)');
|
||||
function desc(x, indentLevel) {
|
||||
indentLevel = indentLevel || 0;
|
||||
var indent = new Array(indentLevel).join(' ');
|
||||
if (typeof x == 'string' || (x && x.__proto__ == String.prototype)) {
|
||||
return indent + '"' + x + '"';
|
||||
}
|
||||
else if (Array.isArray(x)) {
|
||||
return indent + '[ ' + x.map(desc).join(', ') + ' ]';
|
||||
}
|
||||
else {
|
||||
return '' + x;
|
||||
}
|
||||
}
|
||||
|
||||
function assertEqual(a, b) {
|
||||
if (a !== b) throw new Error('assertion failed, ' + a + ' !== ' + b);
|
||||
function assertFormat(args, expected) {
|
||||
var fmt = args[0];
|
||||
var result = format.format.apply(format, args);
|
||||
if (result !== expected) {
|
||||
console.log('FORMAT: "' + fmt + '"');
|
||||
console.log('ARGS: ' + desc(args.slice(1)));
|
||||
console.log('RESULT: "' + result + '"');
|
||||
throw new Error('assertion failed, ' + result + ' !== ' + expected);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Testing format:');
|
||||
assertEqual(format.format('hello'), 'hello');
|
||||
assertEqual(format.format('hello %s', 'sami'), 'hello sami');
|
||||
assertEqual(format.format('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), "b: 101010\nc: A\nd: 1764\nf: 0.000074\no: 0377\ns: sami\nx: 0xfeedface\nX: 0xC0FFEE");
|
||||
console.log('(pass)');
|
||||
|
||||
var tests = [
|
||||
[['hello'], 'hello'],
|
||||
[['hello %s', 'sami'], 'hello sami'],
|
||||
[
|
||||
['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],
|
||||
"b: 101010\nc: A\nd: 1764\nf: 0.000074\no: 0377\ns: sami\nx: 0xfeedface\nX: 0xC0FFEE"
|
||||
],
|
||||
[['%.2f', 3.14159], '3.14'],
|
||||
[['%0.2f', 3.14159], '3.14'],
|
||||
[['%.2f', 0.1234], '.12'],
|
||||
[['%0.2f', 0.1234], '0.12'],
|
||||
[['foo %j', 42], 'foo 42'],
|
||||
[['foo %j', '42'], 'foo "42"']
|
||||
];
|
||||
tests.forEach(function(spec) {
|
||||
var args = spec[0];
|
||||
var expected = spec[1];
|
||||
assertFormat(args, expected);
|
||||
console.log('pass (format ' + args[0] + ' == ' + expected + ')');
|
||||
});
|
||||
|
||||
console.log('all passed');
|
||||
|
|
|
|||
Loading…
Reference in a new issue