Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

sprintf-js

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sprintf-js - npm Package Compare versions

Comparing version 1.1.0 to 1.1.1

.eslintignore

5

benchmark/benchmark.js
var Benchmark = require('benchmark'),
suite = new Benchmark.Suite,
sprintfjs = require("../src/sprintf.js"),
sprintf = sprintfjs.sprintf,
vsprintf = sprintfjs.vsprintf
sprintfjs = require('../src/sprintf.js'),
sprintf = sprintfjs.sprintf

@@ -7,0 +6,0 @@ suite

2

bower.json
{
"name": "sprintf",
"description": "JavaScript sprintf implementation",
"version": "1.0.3",
"version": "1.1.1",
"main": [

@@ -6,0 +6,0 @@ "dist/sprintf.min.js",

@@ -1,3 +0,3 @@

/*! sprintf-js v1.1.0 | Copyright (c) 2007-present, Alexandru Marasteanu <hello@alexei.ro> | BSD-3-Clause */
/*! sprintf-js v1.1.1 | Copyright (c) 2007-present, Alexandru Mărășteanu <hello@alexei.ro> | BSD-3-Clause */
!function(){"use strict";angular.module("sprintf",[]).filter("sprintf",function(){return function(){return sprintf.apply(null,arguments)}}).filter("fmt",["$filter",function(t){return t("sprintf")}]).filter("vsprintf",function(){return function(t,n){return vsprintf(t,n)}}).filter("vfmt",["$filter",function(t){return t("vsprintf")}])}();
//# sourceMappingURL=angular-sprintf.min.js.map

@@ -1,3 +0,3 @@

/*! sprintf-js v1.1.0 | Copyright (c) 2007-present, Alexandru Marasteanu <hello@alexei.ro> | BSD-3-Clause */
!function(e){"use strict";function t(){var e=arguments[0],r=t.cache;return r[e]||(r[e]=t.parse(e)),t.format.call(null,r[e],arguments)}function r(e){return"number"==typeof e?"number":"string"==typeof e?"string":Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function n(e,t){return t>=0&&t<=7&&i[e]?i[e][t]:Array(t+1).join(e)}var s={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:/^[\+\-]/};t.format=function(e,a){var i,o,l,c,p,f,u,g=1,_=e.length,d="",b=[],h=!0,x="";for(o=0;o<_;o++)if("string"===(d=r(e[o])))b[b.length]=e[o];else if("array"===d){if(c=e[o],c[2])for(i=a[g],l=0;l<c[2].length;l++){if(!i.hasOwnProperty(c[2][l]))throw new Error(t('[sprintf] property "%s" does not exist',c[2][l]));i=i[c[2][l]]}else i=c[1]?a[c[1]]:a[g++];if(s.not_type.test(c[8])&&s.not_primitive.test(c[8])&&"function"==r(i)&&(i=i()),s.numeric_arg.test(c[8])&&"number"!=r(i)&&isNaN(i))throw new TypeError(t("[sprintf] expecting number but found %s",r(i)));switch(s.number.test(c[8])&&(h=i>=0),c[8]){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,c[6]?parseInt(c[6]):0);break;case"e":i=c[7]?parseFloat(i).toExponential(c[7]):parseFloat(i).toExponential();break;case"f":i=c[7]?parseFloat(i).toFixed(c[7]):parseFloat(i);break;case"g":i=c[7]?parseFloat(i).toPrecision(c[7]):parseFloat(i);break;case"o":i=i.toString(8);break;case"s":i=String(i),i=c[7]?i.substring(0,c[7]):i;break;case"t":i=String(!!i),i=c[7]?i.substring(0,c[7]):i;break;case"T":i=r(i),i=c[7]?i.substring(0,c[7]):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=c[7]?i.substring(0,c[7]):i;break;case"x":i=parseInt(i,10).toString(16);break;case"X":i=parseInt(i,10).toString(16).toUpperCase()}s.json.test(c[8])?b[b.length]=i:(!s.number.test(c[8])||h&&!c[3]?x="":(x=h?"+":"-",i=i.toString().replace(s.sign,"")),f=c[4]?"0"===c[4]?"0":c[4].charAt(1):" ",u=c[6]-(x+i).length,p=c[6]&&u>0?n(f,u):"",b[b.length]=c[5]?x+i+p:"0"===f?x+p+i:p+x+i)}return b.join("")},t.cache=Object.create(null),t.parse=function(e){for(var t=e,r=[],n=[],a=0;t;){if(null!==(r=s.text.exec(t)))n[n.length]=r[0];else if(null!==(r=s.modulo.exec(t)))n[n.length]="%";else{if(null===(r=s.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){a|=1;var i=[],o=r[2],l=[];if(null===(l=s.key.exec(o)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(i[i.length]=l[1];""!==(o=o.substring(l[0].length));)if(null!==(l=s.key_access.exec(o)))i[i.length]=l[1];else{if(null===(l=s.index_access.exec(o)))throw new SyntaxError("[sprintf] failed to parse named argument key");i[i.length]=l[1]}r[2]=i}else a|=2;if(3===a)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n[n.length]=r}t=t.substring(r[0].length)}return n};var a=function(e,r,n){return n=(r||[]).slice(0),n.splice(0,0,e),t.apply(null,n)},i={0:["","0","00","000","0000","00000","000000","0000000"]," ":[""," "," "," "," "," "," "," "],_:["","_","__","___","____","_____","______","_______"]};"undefined"!=typeof exports&&(exports.sprintf=t,exports.vsprintf=a),void 0!==e&&(e.sprintf=t,e.vsprintf=a,"function"==typeof define&&define.amd&&define(function(){return{sprintf:t,vsprintf:a}}))}("undefined"==typeof window?this:window);
/*! sprintf-js v1.1.1 | Copyright (c) 2007-present, Alexandru Mărășteanu <hello@alexei.ro> | BSD-3-Clause */
!function(){"use strict";function e(e){return r(n(e),arguments)}function t(t,r){return e.apply(null,[t].concat(r||[]))}function r(t,r){var n,i,a,o,p,c,u,f,l,d=1,g=t.length,b="";for(i=0;i<g;i++)if("string"==typeof t[i])b+=t[i];else if(Array.isArray(t[i])){if((o=t[i])[2])for(n=r[d],a=0;a<o[2].length;a++){if(!n.hasOwnProperty(o[2][a]))throw new Error(e('[sprintf] property "%s" does not exist',o[2][a]));n=n[o[2][a]]}else n=o[1]?r[o[1]]:r[d++];if(s.not_type.test(o[8])&&s.not_primitive.test(o[8])&&n instanceof Function&&(n=n()),s.numeric_arg.test(o[8])&&"number"!=typeof n&&isNaN(n))throw new TypeError(e("[sprintf] expecting number but found %T",n));switch(s.number.test(o[8])&&(f=n>=0),o[8]){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,o[6]?parseInt(o[6]):0);break;case"e":n=o[7]?parseFloat(n).toExponential(o[7]):parseFloat(n).toExponential();break;case"f":n=o[7]?parseFloat(n).toFixed(o[7]):parseFloat(n);break;case"g":n=o[7]?String(Number(n.toPrecision(o[7]))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=o[7]?n.substring(0,o[7]):n;break;case"t":n=String(!!n),n=o[7]?n.substring(0,o[7]):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=o[7]?n.substring(0,o[7]):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=o[7]?n.substring(0,o[7]):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}s.json.test(o[8])?b+=n:(!s.number.test(o[8])||f&&!o[3]?l="":(l=f?"+":"-",n=n.toString().replace(s.sign,"")),c=o[4]?"0"===o[4]?"0":o[4].charAt(1):" ",u=o[6]-(l+n).length,p=o[6]&&u>0?c.repeat(u):"",b+=o[5]?l+n+p:"0"===c?l+p+n:p+l+n)}return b}function n(e){if(i[e])return i[e];for(var t,r=e,n=[],a=0;r;){if(null!==(t=s.text.exec(r)))n.push(t[0]);else if(null!==(t=s.modulo.exec(r)))n.push("%");else{if(null===(t=s.placeholder.exec(r)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){a|=1;var o=[],p=t[2],c=[];if(null===(c=s.key.exec(p)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(o.push(c[1]);""!==(p=p.substring(c[0].length));)if(null!==(c=s.key_access.exec(p)))o.push(c[1]);else{if(null===(c=s.index_access.exec(p)))throw new SyntaxError("[sprintf] failed to parse named argument key");o.push(c[1])}t[2]=o}else a|=2;if(3===a)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n.push(t)}r=r.substring(t[0].length)}return i[e]=n}var s={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:/^[\+\-]/},i=Object.create(null);"undefined"!=typeof exports&&(exports.sprintf=e,exports.vsprintf=t),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=t,"function"==typeof define&&define.amd&&define(function(){return{sprintf:e,vsprintf:t}}))}();
//# sourceMappingURL=sprintf.min.js.map

@@ -9,3 +9,3 @@ 'use strict'

header = require('gulp-header'),
jshint = require('gulp-jshint'),
eslint = require('gulp-eslint'),
mocha = require('gulp-mocha'),

@@ -19,3 +19,3 @@ benchmark = require('gulp-benchmark'),

.pipe(benchmark())
});
})

@@ -25,4 +25,4 @@ gulp.task('lint', function() {

.src('src/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(eslint())
.pipe(eslint.format())
})

@@ -33,3 +33,3 @@

.src('test/*.js', {read: false})
.pipe(mocha({reporter: 'nyan'}));
.pipe(mocha({reporter: 'nyan'}))
})

@@ -39,4 +39,4 @@

return gulp.src([
'src/*.js'
])
'src/*.js'
])
.pipe(sourcemaps.init())

@@ -43,0 +43,0 @@ .pipe(uglify())

{
"name": "sprintf-js",
"version": "1.1.0",
"version": "1.1.1",
"description": "JavaScript sprintf implementation",
"author": "Alexandru Marasteanu <hello@alexei.ro>",
"author": "Alexandru Mărășteanu <hello@alexei.ro>",
"main": "src/sprintf.js",
"scripts": {
"test": "mocha test/test.js"
"test": "mocha test/test.js",
"posttest": "npm run lint",
"lint": "eslint .",
"lint:fix": "eslint --fix ."
},

@@ -18,13 +21,13 @@ "repository": {

"benchmark": "^2.1.4",
"gulp": "^3.9.0",
"eslint": "3.19.0",
"gulp": "^3.9.1",
"gulp-benchmark": "^1.1.1",
"gulp-header": "^1.7.1",
"gulp-jshint": "^2.0.0",
"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": "^2.1.2",
"jshint": "^2.9.1",
"mocha": "^3.3.0"
"gulp-uglify": "^3.0.0",
"mocha": "^3.4.2"
}
}

@@ -1,3 +0,6 @@

# sprintf.js [![NPM Version][npm-image]][npm-url] [![Dependency Status][dependencies-image]][dependencies-url] [![devDependency Status][dev-dependencies-image]][dev-dependencies-url]
# 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

@@ -4,0 +7,0 @@ [npm-url]: https://badge.fury.io/js/sprintf-js

@@ -1,4 +0,4 @@

/* globals angular, sprintf, vsprintf */
/* global angular, sprintf, vsprintf */
(function () {
!function () {
'use strict'

@@ -24,2 +24,2 @@

}])
})();
}()

@@ -1,4 +0,4 @@

/* globals window, exports, define */
/* global window, exports, define */
(function(window) {
!function() {
'use strict'

@@ -24,18 +24,18 @@

function sprintf() {
var key = arguments[0], cache = sprintf.cache
if (!(cache[key])) {
cache[key] = sprintf.parse(key)
}
return sprintf.format.call(null, cache[key], arguments)
function sprintf(key) {
// `arguments` is not an array, but should be fine for this call
return sprintf_format(sprintf_parse(key), arguments)
}
sprintf.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = ''
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++) {
node_type = get_type(parse_tree[i])
if (node_type === 'string') {
output[output.length] = parse_tree[i]
if (typeof parse_tree[i] === 'string') {
output += parse_tree[i]
}
else if (node_type === 'array') {
else if (Array.isArray(parse_tree[i])) {
match = parse_tree[i] // convenience purposes only

@@ -58,8 +58,8 @@ if (match[2]) { // keyword argument

if (re.not_type.test(match[8]) && re.not_primitive.test(match[8]) && get_type(arg) == 'function') {
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]) && (get_type(arg) != 'number' && isNaN(arg))) {
throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg)))
if (re.numeric_arg.test(match[8]) && (typeof arg !== 'number' && isNaN(arg))) {
throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
}

@@ -74,53 +74,53 @@

arg = parseInt(arg, 10).toString(2)
break
break
case 'c':
arg = String.fromCharCode(parseInt(arg, 10))
break
break
case 'd':
case 'i':
arg = parseInt(arg, 10)
break
break
case 'j':
arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0)
break
break
case 'e':
arg = match[7] ? parseFloat(arg).toExponential(match[7]) : parseFloat(arg).toExponential()
break
break
case 'f':
arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg)
break
break
case 'g':
arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg)
break
arg = match[7] ? String(Number(arg.toPrecision(match[7]))) : parseFloat(arg)
break
case 'o':
arg = arg.toString(8)
break
arg = (parseInt(arg, 10) >>> 0).toString(8)
break
case 's':
arg = String(arg)
arg = (match[7] ? arg.substring(0, match[7]) : arg)
break
break
case 't':
arg = String(!!arg)
arg = (match[7] ? arg.substring(0, match[7]) : arg)
break
break
case 'T':
arg = get_type(arg)
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
arg = (match[7] ? arg.substring(0, match[7]) : arg)
break
break
case 'u':
arg = parseInt(arg, 10) >>> 0
break
break
case 'v':
arg = arg.valueOf()
arg = (match[7] ? arg.substring(0, match[7]) : arg)
break
break
case 'x':
arg = parseInt(arg, 10).toString(16)
break
arg = (parseInt(arg, 10) >>> 0).toString(16)
break
case 'X':
arg = parseInt(arg, 10).toString(16).toUpperCase()
break
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
break
}
if (re.json.test(match[8])) {
output[output.length] = arg
output += arg
}

@@ -137,20 +137,24 @@ else {

pad_length = match[6] - (sign + arg).length
pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : '') : ''
output[output.length] = match[5] ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
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.join('')
return output
}
sprintf.cache = Object.create(null)
var sprintf_cache = Object.create(null)
sprintf.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0
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[parse_tree.length] = match[0]
parse_tree.push(match[0])
}
else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree[parse_tree.length] = '%'
parse_tree.push('%')
}

@@ -162,12 +166,12 @@ else if ((match = re.placeholder.exec(_fmt)) !== null) {

if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list[field_list.length] = field_match[1]
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[field_list.length] = field_match[1]
field_list.push(field_match[1])
}
else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
field_list[field_list.length] = field_match[1]
field_list.push(field_match[1])
}
else {
throw new SyntaxError("[sprintf] failed to parse named argument key")
throw new SyntaxError('[sprintf] failed to parse named argument key')
}

@@ -177,3 +181,3 @@ }

else {
throw new SyntaxError("[sprintf] failed to parse named argument key")
throw new SyntaxError('[sprintf] failed to parse named argument key')
}

@@ -186,63 +190,31 @@ match[2] = field_list

if (arg_names === 3) {
throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported")
throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
}
parse_tree[parse_tree.length] = match
parse_tree.push(match)
}
else {
throw new SyntaxError("[sprintf] unexpected placeholder")
throw new SyntaxError('[sprintf] unexpected placeholder')
}
_fmt = _fmt.substring(match[0].length)
}
return parse_tree
return sprintf_cache[fmt] = parse_tree
}
var vsprintf = function(fmt, argv, _argv) {
_argv = (argv || []).slice(0)
_argv.splice(0, 0, fmt)
return sprintf.apply(null, _argv)
}
/**
* helpers
*/
function get_type(variable) {
if (typeof variable === 'number') {
return 'number'
}
else if (typeof variable === 'string') {
return 'string'
}
else {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase()
}
}
var preformattedPadding = {
'0': ['', '0', '00', '000', '0000', '00000', '000000', '0000000'],
' ': ['', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
'_': ['', '_', '__', '___', '____', '_____', '______', '_______'],
}
function str_repeat(input, multiplier) {
if (multiplier >= 0 && multiplier <= 7 && preformattedPadding[input]) {
return preformattedPadding[input][multiplier]
}
return Array(multiplier + 1).join(input)
}
/**
* export to either browser or node.js
*/
/* eslint-disable quote-props */
if (typeof exports !== 'undefined') {
exports.sprintf = sprintf
exports.vsprintf = vsprintf
exports['sprintf'] = sprintf
exports['vsprintf'] = vsprintf
}
if (typeof window !== 'undefined') {
window.sprintf = sprintf
window.vsprintf = vsprintf
window['sprintf'] = sprintf
window['vsprintf'] = vsprintf
if (typeof define === 'function' && define.amd) {
if (typeof define === 'function' && define['amd']) {
define(function() {
return {
sprintf: sprintf,
vsprintf: vsprintf
'sprintf': sprintf,
'vsprintf': vsprintf
}

@@ -252,2 +224,3 @@ })

}
})(typeof window === 'undefined' ? this : window);
/* eslint-enable quote-props */
}()

@@ -1,3 +0,5 @@

'use strict';
/* global describe, it */
'use strict'
var assert = require('assert'),

@@ -16,41 +18,41 @@ sprintfjs = require('../src/sprintf.js'),

describe("sprintfjs cache", function() {
describe('sprintfjs cache', function() {
it("should not throw Error (cache consistency)", 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?"])
sprintf('hasOwnProperty')
sprintf('constructor')
should_not_throw('%s', ['caching...'])
should_not_throw('%s', ['crash?'])
})
})
describe("sprintfjs", function() {
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)
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("")
var numeric = 'bcdiefguxX'.split('')
numeric.forEach(function(specifier) {
var fmt = sprintf("%%%s",specifier)
it(fmt + " should throw TypeError for invalid numbers", function() {
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, ['str'], TypeError)
should_throw(fmt, [{}], TypeError)
should_throw(fmt, ["s"], TypeError)
should_throw(fmt, ['s'], TypeError)
})
it(fmt + " should not throw TypeError for something implicitly castable to number", function() {
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, ['200'])
should_not_throw(fmt, [null])

@@ -57,0 +59,0 @@ })

@@ -1,40 +0,44 @@

'use strict';
/* global describe, it */
var assert = require("assert"),
sprintfjs = require("../src/sprintf.js"),
sprintf = sprintfjs.sprintf,
vsprintf = sprintfjs.vsprintf
'use strict'
describe("sprintfjs", function() {
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("%s", sprintf("%s", "%s"))
assert.equal("ff", sprintf("%x", 255))
assert.equal("FF", 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))
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))

@@ -45,11 +49,11 @@ assert.equal('undefined', sprintf('%T', undefined))

assert.equal('number', sprintf('%T', 42))
assert.equal('string', sprintf('%T', "This is a string"))
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('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('This is a string', sprintf('%v', 'This is a string'))
assert.equal('1,2,3', sprintf('%v', [1, 2, 3]))

@@ -60,52 +64,51 @@ assert.equal('[object Object]', sprintf('%v', {foo: 'bar'}))

it("should return formated strings for complex placeholders", function() {
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))
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"]))
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"))
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" }))
assert.equal(Date.now(), sprintf("%s", Date.now)) // should pass...
it('should return formated strings for callbacks', function() {
assert.equal('foobar', sprintf('%s', function() { return 'foobar' }))
})
})

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc