sprintf.js-1.1.1/000077500000000000000000000000001311304505100136035ustar00rootroot00000000000000sprintf.js-1.1.1/.editorconfig000066400000000000000000000004731311304505100162640ustar00rootroot00000000000000# EditorConfig defines and maintains consistent coding styles between different # editors and IDEs: http://EditorConfig.org/ # Top-most EditorConfig file root = true # All files [*] charset = utf-8 end_of_line = lf insert_final_newline = true indent_style = space indent_size = 4 trim_trailing_whitespace = true sprintf.js-1.1.1/.eslintignore000066400000000000000000000000261311304505100163040ustar00rootroot00000000000000dist/* node_modules/* sprintf.js-1.1.1/.eslintrc.js000066400000000000000000000006271311304505100160470ustar00rootroot00000000000000module.exports = { extends: 'eslint:recommended', env: { node: true, es6: true }, rules: { indent: ['error', 4, {SwitchCase: 1}], 'quote-props': ['error', 'as-needed'], 'no-cond-assign': 0, 'no-console': 0, 'no-control-regex': 0, 'no-undef': 'error', 'no-unused-vars': 'error', semi: ['error', 'never'] } } sprintf.js-1.1.1/.gitignore000066400000000000000000000000161311304505100155700ustar00rootroot00000000000000/node_modules/sprintf.js-1.1.1/.travis.yml000066400000000000000000000000461311304505100157140ustar00rootroot00000000000000language: node_js node_js: - "node" sprintf.js-1.1.1/CHANGELOG.md000066400000000000000000000002561311304505100154170ustar00rootroot00000000000000## 1.1.1 (2017-05-29) * This CHANGELOG * Various optimizations for modern browsers * Fix %g, %o, %x and %X specifiers * Use ESLint instead of JSHint * Add CONTRIBUTORS file sprintf.js-1.1.1/CONTRIBUTORS000066400000000000000000000015601311304505100154650ustar00rootroot00000000000000Alexander Rose Alexandru Mărășteanu Andras @andrasq Benoit Giannangeli https://github.com/giann Branden Visser David Baird daurnimator Doug Beck https://github.com/beck Dzmitry Litskalau https://github.com/litmit Hans Pufal Henry https://github.com/alograg Johnny Shields Kamal Abdali Matt Simerson https://github.com/msimerson Maxime Robert https://github.com/marob MeriemKhelifi https://github.com/MeriemKhelifi Michael Schramm Nazar Mokrynskyi Oliver Salzburg Pablo Rabehaja Stevens https://github.com/RABEHAJA-STEVENS Raphael Pigulla https://github.com/pigulla rebeccapeltz https://github.com/rebeccapeltz Stefan Tingström https://github.com/stingstrom sprintf.js-1.1.1/LICENSE000066400000000000000000000027511311304505100146150ustar00rootroot00000000000000Copyright (c) 2007-present, Alexandru Mărășteanu All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of this software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. sprintf.js-1.1.1/README.md000066400000000000000000000136151311304505100150700ustar00rootroot00000000000000# sprintf.js [![Build Status][travisci-image]][travisci-url] [![NPM Version][npm-image]][npm-url] [![Dependency Status][dependencies-image]][dependencies-url] [![devDependency Status][dev-dependencies-image]][dev-dependencies-url] [travisci-image]: https://travis-ci.org/alexei/sprintf.js.svg?branch=master [travisci-url]: https://travis-ci.org/alexei/sprintf.js [npm-image]: https://badge.fury.io/js/sprintf-js.svg [npm-url]: https://badge.fury.io/js/sprintf-js [dependencies-image]: https://david-dm.org/alexei/sprintf.js.svg [dependencies-url]: https://david-dm.org/alexei/sprintf.js [dev-dependencies-image]: https://david-dm.org/alexei/sprintf.js/dev-status.svg [dev-dependencies-url]: https://david-dm.org/alexei/sprintf.js#info=devDependencies **sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. Its prototype is simple: string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: * An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. * An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. * An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. * An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. * An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. * An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. * A type specifier that can be any of: * `%` — yields a literal `%` character * `b` — yields an integer as a binary number * `c` — yields an integer as the character with that ASCII value * `d` or `i` — yields an integer as a signed decimal number * `e` — yields a float using scientific notation * `u` — yields an integer as an unsigned decimal number * `f` — yields a float as is; see notes on precision above * `g` — yields a float as is; see notes on precision above * `o` — yields an integer as an octal number * `s` — yields a string as is * `t` — yields `true` or `false` * `T` — yields the type of the argument1 * `v` — yields the primitive value of the specified argument * `x` — yields an integer as a hexadecimal number (lower-case) * `X` — yields an integer as a hexadecimal number (upper-case) * `j` — yields a JavaScript object or array as a JSON encoded string ## JavaScript `vsprintf` `vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) ## Argument swapping You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") And, of course, you can repeat the placeholders without having to increase the number of arguments. ## Named arguments Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: var user = { name: "Dolly" } sprintf("Hello %(name)s", user) // Hello Dolly Keywords in replacement fields can be optionally followed by any number of keywords or indexes: var users = [ {name: "Dolly"}, {name: "Molly"}, {name: "Polly"} ] sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly Note: mixing positional and named placeholders is not (yet) supported ## Computed values You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 sprintf("Current date and time: %s", function() { return new Date().toString() }) # AngularJS You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. # Installation ## Via Bower bower install sprintf ## Or as a node.js module npm install sprintf-js ### Usage var sprintf = require("sprintf-js").sprintf, vsprintf = require("sprintf-js").vsprintf sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) # License **sprintf.js** is licensed under the terms of the 3-clause BSD license. # Notes 1 `sprintf` doesn't use the `typeof` operator. As such, the value `null` is a `null`, an array is an `array` (not an `object`), a date value is a `date` etc. sprintf.js-1.1.1/benchmark/000077500000000000000000000000001311304505100155355ustar00rootroot00000000000000sprintf.js-1.1.1/benchmark/benchmark.js000066400000000000000000000010261311304505100200240ustar00rootroot00000000000000var Benchmark = require('benchmark'), suite = new Benchmark.Suite, sprintfjs = require('../src/sprintf.js'), sprintf = sprintfjs.sprintf suite .add('%8d', function() { sprintf('%8d', 12345) }) .add('%08d', function() { sprintf('%08d', 12345) }) .add('%2d', function() { sprintf('%2d', 12345) }) .add('%8s', function() { sprintf('%8s', 'abcde') }) .add('%+010d', function() { sprintf('%+010d', 12345) }) module.exports = suite sprintf.js-1.1.1/bower.json000066400000000000000000000007711311304505100156210ustar00rootroot00000000000000{ "name": "sprintf", "description": "JavaScript sprintf implementation", "version": "1.1.1", "main": [ "dist/sprintf.min.js", "dist/angular-sprintf.min.js" ], "license": "BSD-3-Clause-Clear", "keywords": ["sprintf", "string", "formatting"], "authors": ["Alexandru Marasteanu (http://alexei.ro/)"], "homepage": "https://github.com/alexei/sprintf.js", "repository": { "type": "git", "url": "git://github.com/alexei/sprintf.js.git" }, "ignore": [] } sprintf.js-1.1.1/demo/000077500000000000000000000000001311304505100145275ustar00rootroot00000000000000sprintf.js-1.1.1/demo/angular.html000066400000000000000000000012621311304505100170470ustar00rootroot00000000000000
{{ "%+010d"|sprintf:-123 }}
{{ "%+010d"|vsprintf:[-123] }}
{{ "%+010d"|fmt:-123 }}
{{ "%+010d"|vfmt:[-123] }}
{{ "I've got %2$d apples and %1$d oranges."|fmt:4:2 }}
{{ "I've got %(apples)d apples and %(oranges)d oranges."|fmt:{apples: 2, oranges: 4} }}
sprintf.js-1.1.1/dist/000077500000000000000000000000001311304505100145465ustar00rootroot00000000000000sprintf.js-1.1.1/dist/.gitattributes000066400000000000000000000001521311304505100174370ustar00rootroot00000000000000#ignore all generated files from diff #also skip line ending check *.js -diff -text *.map -diff -text sprintf.js-1.1.1/gulpfile.js000066400000000000000000000023641311304505100157550ustar00rootroot00000000000000'use strict' var pkg = require('./package.json'), gulp = require('gulp'), uglify = require('gulp-uglify'), rename = require('gulp-rename'), sourcemaps = require('gulp-sourcemaps'), header = require('gulp-header'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'), benchmark = require('gulp-benchmark'), banner = '/*! <%= pkg.name %> v<%= pkg.version %> | Copyright (c) 2007-present, <%= pkg.author %> | <%= pkg.license %> */\n' gulp.task('benchmark', function () { return gulp .src('benchmark/*.js', {read: false}) .pipe(benchmark()) }) gulp.task('lint', function() { return gulp .src('src/*.js') .pipe(eslint()) .pipe(eslint.format()) }) gulp.task('test', ['lint'], function() { return gulp .src('test/*.js', {read: false}) .pipe(mocha({reporter: 'nyan'})) }) gulp.task('dist', ['test'], function() { return gulp.src([ 'src/*.js' ]) .pipe(sourcemaps.init()) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(header(banner, {pkg: pkg})) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('dist')) }) gulp.task('default', ['dist']) sprintf.js-1.1.1/package.json000066400000000000000000000014651311304505100160770ustar00rootroot00000000000000{ "name": "sprintf-js", "version": "1.1.1", "description": "JavaScript sprintf implementation", "author": "Alexandru Mărășteanu ", "main": "src/sprintf.js", "scripts": { "test": "mocha test/test.js", "posttest": "npm run lint", "lint": "eslint .", "lint:fix": "eslint --fix ." }, "repository": { "type": "git", "url": "https://github.com/alexei/sprintf.js.git" }, "license": "BSD-3-Clause", "readmeFilename": "README.md", "devDependencies": { "benchmark": "^2.1.4", "eslint": "3.19.0", "gulp": "^3.9.1", "gulp-benchmark": "^1.1.1", "gulp-eslint": "^3.0.1", "gulp-header": "^1.8.8", "gulp-mocha": "^4.3.1", "gulp-rename": "^1.2.2", "gulp-sourcemaps": "^2.6.0", "gulp-uglify": "^3.0.0", "mocha": "^3.4.2" } } sprintf.js-1.1.1/src/000077500000000000000000000000001311304505100143725ustar00rootroot00000000000000sprintf.js-1.1.1/src/angular-sprintf.js000066400000000000000000000012001311304505100200350ustar00rootroot00000000000000/* global angular, sprintf, vsprintf */ !function () { 'use strict' angular. module('sprintf', []). filter('sprintf', function() { return function() { return sprintf.apply(null, arguments) } }). filter('fmt', ['$filter', function($filter) { return $filter('sprintf') }]). filter('vsprintf', function() { return function(format, argv) { return vsprintf(format, argv) } }). filter('vfmt', ['$filter', function($filter) { return $filter('vsprintf') }]) }() sprintf.js-1.1.1/src/sprintf.js000066400000000000000000000207371311304505100164260ustar00rootroot00000000000000/* global window, exports, define */ !function() { 'use strict' var re = { not_string: /[^s]/, not_bool: /[^t]/, not_type: /[^T]/, not_primitive: /[^v]/, number: /[diefg]/, numeric_arg: /[bcdiefguxX]/, json: /[j]/, not_json: /[^j]/, text: /^[^\x25]+/, modulo: /^\x25{2}/, placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, key: /^([a-z_][a-z_\d]*)/i, key_access: /^\.([a-z_][a-z_\d]*)/i, index_access: /^\[(\d+)\]/, sign: /^[\+\-]/ } function sprintf(key) { // `arguments` is not an array, but should be fine for this call return sprintf_format(sprintf_parse(key), arguments) } function vsprintf(fmt, argv) { return sprintf.apply(null, [fmt].concat(argv || [])) } function sprintf_format(parse_tree, argv) { var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, match, pad, pad_character, pad_length, is_positive, sign for (i = 0; i < tree_length; i++) { if (typeof parse_tree[i] === 'string') { output += parse_tree[i] } else if (Array.isArray(parse_tree[i])) { match = parse_tree[i] // convenience purposes only if (match[2]) { // keyword argument arg = argv[cursor] for (k = 0; k < match[2].length; k++) { if (!arg.hasOwnProperty(match[2][k])) { throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k])) } arg = arg[match[2][k]] } } else if (match[1]) { // positional argument (explicit) arg = argv[match[1]] } else { // positional argument (implicit) arg = argv[cursor++] } if (re.not_type.test(match[8]) && re.not_primitive.test(match[8]) && arg instanceof Function) { arg = arg() } if (re.numeric_arg.test(match[8]) && (typeof arg !== 'number' && isNaN(arg))) { throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) } if (re.number.test(match[8])) { is_positive = arg >= 0 } switch (match[8]) { case 'b': arg = parseInt(arg, 10).toString(2) break case 'c': arg = String.fromCharCode(parseInt(arg, 10)) break case 'd': case 'i': arg = parseInt(arg, 10) break case 'j': arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) break case 'e': arg = match[7] ? parseFloat(arg).toExponential(match[7]) : parseFloat(arg).toExponential() break case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) break case 'g': arg = match[7] ? String(Number(arg.toPrecision(match[7]))) : parseFloat(arg) break case 'o': arg = (parseInt(arg, 10) >>> 0).toString(8) break case 's': arg = String(arg) arg = (match[7] ? arg.substring(0, match[7]) : arg) break case 't': arg = String(!!arg) arg = (match[7] ? arg.substring(0, match[7]) : arg) break case 'T': arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() arg = (match[7] ? arg.substring(0, match[7]) : arg) break case 'u': arg = parseInt(arg, 10) >>> 0 break case 'v': arg = arg.valueOf() arg = (match[7] ? arg.substring(0, match[7]) : arg) break case 'x': arg = (parseInt(arg, 10) >>> 0).toString(16) break case 'X': arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() break } if (re.json.test(match[8])) { output += arg } else { if (re.number.test(match[8]) && (!is_positive || match[3])) { sign = is_positive ? '+' : '-' arg = arg.toString().replace(re.sign, '') } else { sign = '' } pad_character = match[4] ? match[4] === '0' ? '0' : match[4].charAt(1) : ' ' pad_length = match[6] - (sign + arg).length pad = match[6] ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' output += match[5] ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) } } } return output } var sprintf_cache = Object.create(null) function sprintf_parse(fmt) { if (sprintf_cache[fmt]) { return sprintf_cache[fmt] } var _fmt = fmt, match, parse_tree = [], arg_names = 0 while (_fmt) { if ((match = re.text.exec(_fmt)) !== null) { parse_tree.push(match[0]) } else if ((match = re.modulo.exec(_fmt)) !== null) { parse_tree.push('%') } else if ((match = re.placeholder.exec(_fmt)) !== null) { if (match[2]) { arg_names |= 1 var field_list = [], replacement_field = match[2], field_match = [] if ((field_match = re.key.exec(replacement_field)) !== null) { field_list.push(field_match[1]) while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { if ((field_match = re.key_access.exec(replacement_field)) !== null) { field_list.push(field_match[1]) } else if ((field_match = re.index_access.exec(replacement_field)) !== null) { field_list.push(field_match[1]) } else { throw new SyntaxError('[sprintf] failed to parse named argument key') } } } else { throw new SyntaxError('[sprintf] failed to parse named argument key') } match[2] = field_list } else { arg_names |= 2 } if (arg_names === 3) { throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') } parse_tree.push(match) } else { throw new SyntaxError('[sprintf] unexpected placeholder') } _fmt = _fmt.substring(match[0].length) } return sprintf_cache[fmt] = parse_tree } /** * export to either browser or node.js */ /* eslint-disable quote-props */ if (typeof exports !== 'undefined') { exports['sprintf'] = sprintf exports['vsprintf'] = vsprintf } if (typeof window !== 'undefined') { window['sprintf'] = sprintf window['vsprintf'] = vsprintf if (typeof define === 'function' && define['amd']) { define(function() { return { 'sprintf': sprintf, 'vsprintf': vsprintf } }) } } /* eslint-enable quote-props */ }() sprintf.js-1.1.1/test/000077500000000000000000000000001311304505100145625ustar00rootroot00000000000000sprintf.js-1.1.1/test/test.js000066400000000000000000000120571311304505100161040ustar00rootroot00000000000000/* global describe, it */ 'use strict' var assert = require('assert'), sprintfjs = require('../src/sprintf.js'), sprintf = sprintfjs.sprintf describe('sprintfjs', function() { var pi = 3.141592653589793 it('should return formated strings for simple placeholders', function() { assert.equal('%', sprintf('%%')) assert.equal('10', sprintf('%b', 2)) assert.equal('A', sprintf('%c', 65)) assert.equal('2', sprintf('%d', 2)) assert.equal('2', sprintf('%i', 2)) assert.equal('2', sprintf('%d', '2')) assert.equal('2', sprintf('%i', '2')) assert.equal('{"foo":"bar"}', sprintf('%j', {foo: 'bar'})) assert.equal('["foo","bar"]', sprintf('%j', ['foo', 'bar'])) assert.equal('2e+0', sprintf('%e', 2)) assert.equal('2', sprintf('%u', 2)) assert.equal('4294967294', sprintf('%u', -2)) assert.equal('2.2', sprintf('%f', 2.2)) assert.equal('3.141592653589793', sprintf('%g', pi)) assert.equal('10', sprintf('%o', 8)) assert.equal('37777777770', sprintf('%o', -8)) assert.equal('%s', sprintf('%s', '%s')) assert.equal('ff', sprintf('%x', 255)) assert.equal('ffffff01', sprintf('%x', -255)) assert.equal('FF', sprintf('%X', 255)) assert.equal('FFFFFF01', sprintf('%X', -255)) assert.equal('Polly wants a cracker', sprintf('%2$s %3$s a %1$s', 'cracker', 'Polly', 'wants')) assert.equal('Hello world!', sprintf('Hello %(who)s!', {who: 'world'})) assert.equal('true', sprintf('%t', true)) assert.equal('t', sprintf('%.1t', true)) assert.equal('true', sprintf('%t', 'true')) assert.equal('true', sprintf('%t', 1)) assert.equal('false', sprintf('%t', false)) assert.equal('f', sprintf('%.1t', false)) assert.equal('false', sprintf('%t', '')) assert.equal('false', sprintf('%t', 0)) assert.equal('undefined', sprintf('%T', undefined)) assert.equal('null', sprintf('%T', null)) assert.equal('boolean', sprintf('%T', true)) assert.equal('number', sprintf('%T', 42)) assert.equal('string', sprintf('%T', 'This is a string')) assert.equal('function', sprintf('%T', Math.log)) assert.equal('array', sprintf('%T', [1, 2, 3])) assert.equal('object', sprintf('%T', {foo: 'bar'})) assert.equal('regexp', sprintf('%T', /<('[^']*'|'[^']*'|[^''>])*>/)) assert.equal('true', sprintf('%v', true)) assert.equal('42', sprintf('%v', 42)) assert.equal('This is a string', sprintf('%v', 'This is a string')) assert.equal('1,2,3', sprintf('%v', [1, 2, 3])) assert.equal('[object Object]', sprintf('%v', {foo: 'bar'})) assert.equal('/<("[^"]*"|\'[^\']*\'|[^\'">])*>/', sprintf('%v', /<("[^"]*"|'[^']*'|[^'">])*>/)) }) it('should return formated strings for complex placeholders', function() { // sign assert.equal('2', sprintf('%d', 2)) assert.equal('-2', sprintf('%d', -2)) assert.equal('+2', sprintf('%+d', 2)) assert.equal('-2', sprintf('%+d', -2)) assert.equal('2', sprintf('%i', 2)) assert.equal('-2', sprintf('%i', -2)) assert.equal('+2', sprintf('%+i', 2)) assert.equal('-2', sprintf('%+i', -2)) assert.equal('2.2', sprintf('%f', 2.2)) assert.equal('-2.2', sprintf('%f', -2.2)) assert.equal('+2.2', sprintf('%+f', 2.2)) assert.equal('-2.2', sprintf('%+f', -2.2)) assert.equal('-2.3', sprintf('%+.1f', -2.34)) assert.equal('-0.0', sprintf('%+.1f', -0.01)) assert.equal('3.14159', sprintf('%.6g', pi)) assert.equal('3.14', sprintf('%.3g', pi)) assert.equal('3', sprintf('%.1g', pi)) assert.equal('-000000123', sprintf('%+010d', -123)) assert.equal('______-123', sprintf("%+'_10d", -123)) assert.equal('-234.34 123.2', sprintf('%f %f', -234.34, 123.2)) // padding assert.equal('-0002', sprintf('%05d', -2)) assert.equal('-0002', sprintf('%05i', -2)) assert.equal(' <', sprintf('%5s', '<')) assert.equal('0000<', sprintf('%05s', '<')) assert.equal('____<', sprintf("%'_5s", '<')) assert.equal('> ', sprintf('%-5s', '>')) assert.equal('>0000', sprintf('%0-5s', '>')) assert.equal('>____', sprintf("%'_-5s", '>')) assert.equal('xxxxxx', sprintf('%5s', 'xxxxxx')) assert.equal('1234', sprintf('%02u', 1234)) assert.equal(' -10.235', sprintf('%8.3f', -10.23456)) assert.equal('-12.34 xxx', sprintf('%f %s', -12.34, 'xxx')) assert.equal('{\n "foo": "bar"\n}', sprintf('%2j', {foo: 'bar'})) assert.equal('[\n "foo",\n "bar"\n]', sprintf('%2j', ['foo', 'bar'])) // precision assert.equal('2.3', sprintf('%.1f', 2.345)) assert.equal('xxxxx', sprintf('%5.5s', 'xxxxxx')) assert.equal(' x', sprintf('%5.1s', 'xxxxxx')) }) it('should return formated strings for callbacks', function() { assert.equal('foobar', sprintf('%s', function() { return 'foobar' })) }) }) sprintf.js-1.1.1/test/test_validation.js000066400000000000000000000036531311304505100203200ustar00rootroot00000000000000/* global describe, it */ 'use strict' var assert = require('assert'), sprintfjs = require('../src/sprintf.js'), sprintf = sprintfjs.sprintf, vsprintf = sprintfjs.vsprintf function should_throw(format,args,err) { assert.throws(function() { vsprintf(format,args) }, err) } function should_not_throw(format,args) { assert.doesNotThrow(function() { vsprintf(format,args) }) } describe('sprintfjs cache', function() { it('should not throw Error (cache consistency)', function() { // redefine object properties to ensure that is not affect to the cache sprintf('hasOwnProperty') sprintf('constructor') should_not_throw('%s', ['caching...']) should_not_throw('%s', ['crash?']) }) }) describe('sprintfjs', function() { it('should throw SyntaxError for placeholders', function() { should_throw('%', [], SyntaxError) should_throw('%A', [], SyntaxError) should_throw('%s%', [], SyntaxError) should_throw('%(s', [], SyntaxError) should_throw('%)s', [], SyntaxError) should_throw('%$s', [], SyntaxError) should_throw('%()s', [], SyntaxError) should_throw('%(12)s', [], SyntaxError) }) var numeric = 'bcdiefguxX'.split('') numeric.forEach(function(specifier) { var fmt = sprintf('%%%s',specifier) it(fmt + ' should throw TypeError for invalid numbers', function() { should_throw(fmt, [], TypeError) should_throw(fmt, ['str'], TypeError) should_throw(fmt, [{}], TypeError) should_throw(fmt, ['s'], TypeError) }) it(fmt + ' should not throw TypeError for something implicitly castable to number', function() { should_not_throw(fmt, [1/0]) should_not_throw(fmt, [true]) should_not_throw(fmt, [[1]]) should_not_throw(fmt, ['200']) should_not_throw(fmt, [null]) }) }) })