From c62e75d789787cc21438dde943885dda9f0ae387 Mon Sep 17 00:00:00 2001 From: Klaus Weidenbach Date: Thu, 14 May 2015 10:39:56 +0200 Subject: Add sprintf.js v1.0.2. This script provides sprintf() for JavaScript. It can be used for example for translating strings used in JavaScript with variables. It is licensed under BSD-3-Clause and can be found on GitHub: https://github.com/alexei/sprintf.js --- library/sprintf.js/.gitignore | 1 + library/sprintf.js/LICENSE | 24 +++ library/sprintf.js/README.md | 82 ++++++++++ library/sprintf.js/bower.json | 14 ++ library/sprintf.js/demo/angular.html | 20 +++ library/sprintf.js/dist/angular-sprintf.min.js | 4 + library/sprintf.js/dist/angular-sprintf.min.map | 1 + library/sprintf.js/dist/sprintf.min.js | 4 + library/sprintf.js/dist/sprintf.min.map | 1 + library/sprintf.js/gruntfile.js | 36 +++++ library/sprintf.js/package.json | 22 +++ library/sprintf.js/src/angular-sprintf.js | 18 +++ library/sprintf.js/src/sprintf.js | 195 ++++++++++++++++++++++++ library/sprintf.js/test/test.js | 72 +++++++++ 14 files changed, 494 insertions(+) create mode 100644 library/sprintf.js/.gitignore create mode 100644 library/sprintf.js/LICENSE create mode 100644 library/sprintf.js/README.md create mode 100644 library/sprintf.js/bower.json create mode 100644 library/sprintf.js/demo/angular.html create mode 100644 library/sprintf.js/dist/angular-sprintf.min.js create mode 100644 library/sprintf.js/dist/angular-sprintf.min.map create mode 100644 library/sprintf.js/dist/sprintf.min.js create mode 100644 library/sprintf.js/dist/sprintf.min.map create mode 100644 library/sprintf.js/gruntfile.js create mode 100644 library/sprintf.js/package.json create mode 100644 library/sprintf.js/src/angular-sprintf.js create mode 100644 library/sprintf.js/src/sprintf.js create mode 100644 library/sprintf.js/test/test.js (limited to 'library') diff --git a/library/sprintf.js/.gitignore b/library/sprintf.js/.gitignore new file mode 100644 index 000000000..096746c14 --- /dev/null +++ b/library/sprintf.js/.gitignore @@ -0,0 +1 @@ +/node_modules/ \ No newline at end of file diff --git a/library/sprintf.js/LICENSE b/library/sprintf.js/LICENSE new file mode 100644 index 000000000..5c74c8264 --- /dev/null +++ b/library/sprintf.js/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2007-2013, Alexandru Marasteanu +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. diff --git a/library/sprintf.js/README.md b/library/sprintf.js/README.md new file mode 100644 index 000000000..d4c720326 --- /dev/null +++ b/library/sprintf.js/README.md @@ -0,0 +1,82 @@ +# sprintf.js +**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. +* 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 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 + * `o` — yields an integer as an octal number + * `s` — yields a string as is + * `x` — yields an integer as a hexadecimal number (lower-case) + * `X` — yields an integer as a hexadecimal number (upper-case) + +## 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"]) diff --git a/library/sprintf.js/bower.json b/library/sprintf.js/bower.json new file mode 100644 index 000000000..ecdf6d542 --- /dev/null +++ b/library/sprintf.js/bower.json @@ -0,0 +1,14 @@ +{ + "name": "sprintf", + "description": "JavaScript sprintf implementation", + "version": "1.0.2", + "main": "src/sprintf.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" + } +} diff --git a/library/sprintf.js/demo/angular.html b/library/sprintf.js/demo/angular.html new file mode 100644 index 000000000..3559efd76 --- /dev/null +++ b/library/sprintf.js/demo/angular.html @@ -0,0 +1,20 @@ + + + + + + + + +
{{ "%+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} }}
+ + + + diff --git a/library/sprintf.js/dist/angular-sprintf.min.js b/library/sprintf.js/dist/angular-sprintf.min.js new file mode 100644 index 000000000..dbaf744d8 --- /dev/null +++ b/library/sprintf.js/dist/angular-sprintf.min.js @@ -0,0 +1,4 @@ +/*! sprintf-js | Alexandru Marasteanu (http://alexei.ro/) | BSD-3-Clause */ + +angular.module("sprintf",[]).filter("sprintf",function(){return function(){return sprintf.apply(null,arguments)}}).filter("fmt",["$filter",function(a){return a("sprintf")}]).filter("vsprintf",function(){return function(a,b){return vsprintf(a,b)}}).filter("vfmt",["$filter",function(a){return a("vsprintf")}]); +//# sourceMappingURL=angular-sprintf.min.map \ No newline at end of file diff --git a/library/sprintf.js/dist/angular-sprintf.min.map b/library/sprintf.js/dist/angular-sprintf.min.map new file mode 100644 index 000000000..055964c62 --- /dev/null +++ b/library/sprintf.js/dist/angular-sprintf.min.map @@ -0,0 +1 @@ +{"version":3,"file":"angular-sprintf.min.js","sources":["../src/angular-sprintf.js"],"names":["angular","module","filter","sprintf","apply","arguments","$filter","format","argv","vsprintf"],"mappings":";;AAAAA,QACIC,OAAO,cACPC,OAAO,UAAW,WACd,MAAO,YACH,MAAOC,SAAQC,MAAM,KAAMC,cAGnCH,OAAO,OAAQ,UAAW,SAASI,GAC/B,MAAOA,GAAQ,cAEnBJ,OAAO,WAAY,WACf,MAAO,UAASK,EAAQC,GACpB,MAAOC,UAASF,EAAQC,MAGhCN,OAAO,QAAS,UAAW,SAASI,GAChC,MAAOA,GAAQ"} \ No newline at end of file diff --git a/library/sprintf.js/dist/sprintf.min.js b/library/sprintf.js/dist/sprintf.min.js new file mode 100644 index 000000000..d5bcd097f --- /dev/null +++ b/library/sprintf.js/dist/sprintf.min.js @@ -0,0 +1,4 @@ +/*! sprintf-js | Alexandru Marasteanu (http://alexei.ro/) | BSD-3-Clause */ + +!function(a){function b(){var a=arguments[0],c=b.cache;return c[a]&&c.hasOwnProperty(a)||(c[a]=b.parse(a)),b.format.call(null,c[a],arguments)}function c(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}function d(a,b){return Array(b+1).join(a)}var e={not_string:/[^s]/,number:/[dief]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fiosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};b.format=function(a,f){var g,h,i,j,k,l,m,n=1,o=a.length,p="",q=[],r=!0,s="";for(h=0;o>h;h++)if(p=c(a[h]),"string"===p)q[q.length]=a[h];else if("array"===p){if(j=a[h],j[2])for(g=f[n],i=0;i=0),j[8]){case"b":g=g.toString(2);break;case"c":g=String.fromCharCode(g);break;case"d":case"i":g=parseInt(g,10);break;case"e":g=j[7]?g.toExponential(j[7]):g.toExponential();break;case"f":g=j[7]?parseFloat(g).toFixed(j[7]):parseFloat(g);break;case"o":g=g.toString(8);break;case"s":g=(g=String(g))&&j[7]?g.substring(0,j[7]):g;break;case"u":g>>>=0;break;case"x":g=g.toString(16);break;case"X":g=g.toString(16).toUpperCase()}!e.number.test(j[8])||r&&!j[3]?s="":(s=r?"+":"-",g=g.toString().replace(e.sign,"")),l=j[4]?"0"===j[4]?"0":j[4].charAt(1):" ",m=j[6]-(s+g).length,k=j[6]&&m>0?d(l,m):"",q[q.length]=j[5]?s+g+k:"0"===l?s+k+g:k+s+g}return q.join("")},b.cache={},b.parse=function(a){for(var b=a,c=[],d=[],f=0;b;){if(null!==(c=e.text.exec(b)))d[d.length]=c[0];else if(null!==(c=e.modulo.exec(b)))d[d.length]="%";else{if(null===(c=e.placeholder.exec(b)))throw new SyntaxError("[sprintf] unexpected placeholder");if(c[2]){f|=1;var g=[],h=c[2],i=[];if(null===(i=e.key.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(g[g.length]=i[1];""!==(h=h.substring(i[0].length));)if(null!==(i=e.key_access.exec(h)))g[g.length]=i[1];else{if(null===(i=e.index_access.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");g[g.length]=i[1]}c[2]=g}else f|=2;if(3===f)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");d[d.length]=c}b=b.substring(c[0].length)}return d};var f=function(a,c,d){return d=(c||[]).slice(0),d.splice(0,0,a),b.apply(null,d)};"undefined"!=typeof exports?(exports.sprintf=b,exports.vsprintf=f):(a.sprintf=b,a.vsprintf=f,"function"==typeof define&&define.amd&&define(function(){return{sprintf:b,vsprintf:f}}))}("undefined"==typeof window?this:window); +//# sourceMappingURL=sprintf.min.map \ No newline at end of file diff --git a/library/sprintf.js/dist/sprintf.min.map b/library/sprintf.js/dist/sprintf.min.map new file mode 100644 index 000000000..33fe1636d --- /dev/null +++ b/library/sprintf.js/dist/sprintf.min.map @@ -0,0 +1 @@ +{"version":3,"file":"sprintf.min.js","sources":["../src/sprintf.js"],"names":["window","sprintf","key","arguments","cache","hasOwnProperty","parse","format","call","get_type","variable","Object","prototype","toString","slice","toLowerCase","str_repeat","input","multiplier","Array","join","re","not_string","number","text","modulo","placeholder","key_access","index_access","sign","parse_tree","argv","arg","i","k","match","pad","pad_character","pad_length","cursor","tree_length","length","node_type","output","is_positive","Error","test","isNaN","TypeError","String","fromCharCode","parseInt","toExponential","parseFloat","toFixed","substring","toUpperCase","replace","charAt","fmt","_fmt","arg_names","exec","SyntaxError","field_list","replacement_field","field_match","vsprintf","_argv","splice","apply","exports","define","amd","this"],"mappings":";;CAAA,SAAUA,GAaN,QAASC,KACL,GAAIC,GAAMC,UAAU,GAAIC,EAAQH,EAAQG,KAIxC,OAHMA,GAAMF,IAAQE,EAAMC,eAAeH,KACrCE,EAAMF,GAAOD,EAAQK,MAAMJ,IAExBD,EAAQM,OAAOC,KAAK,KAAMJ,EAAMF,GAAMC,WAoJjD,QAASM,GAASC,GACd,MAAOC,QAAOC,UAAUC,SAASL,KAAKE,GAAUI,MAAM,EAA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EAAWW,QAAU,QAE/B,CAAA,GAA4C,QAAvCN,EAAQd,EAAGK,YAAYoC,KAAKF,IAgClC,KAAM,IAAIG,aAAY,mCA/BtB,IAAI5B,EAAM,GAAI,CACV0B,GAAa,CACb,IAAIG,MAAiBC,EAAoB9B,EAAM,GAAI+B,IACnD,IAAuD,QAAlDA,EAAc7C,EAAGnB,IAAI4D,KAAKG,IAe3B,KAAM,IAAIF,aAAY,+CAbtB,KADAC,EAAWA,EAAWvB,QAAUyB,EAAY,GACwC,MAA5ED,EAAoBA,EAAkBV,UAAUW,EAAY,GAAGzB,UACnE,GAA8D,QAAzDyB,EAAc7C,EAAGM,WAAWmC,KAAKG,IAClCD,EAAWA,EAAWvB,QAAUyB,EAAY,OAE3C,CAAA,GAAgE,QAA3DA,EAAc7C,EAAGO,aAAakC,KAAKG,IAIzC,KAAM,IAAIF,aAAY,+CAHtBC,GAAWA,EAAWvB,QAAUyB,EAAY,GAUxD/B,EAAM,GAAK6B,MAGXH,IAAa,CAEjB,IAAkB,IAAdA,EACA,KAAM,IAAIhB,OAAM,4EAEpBf,GAAWA,EAAWW,QAAUN,EAKpCyB,EAAOA,EAAKL,UAAUpB,EAAM,GAAGM,QAEnC,MAAOX,GAGX,IAAIqC,GAAW,SAASR,EAAK5B,EAAMqC,GAG/B,MAFAA,IAASrC,OAAYjB,MAAM,GAC3BsD,EAAMC,OAAO,EAAG,EAAGV,GACZ1D,EAAQqE,MAAM,KAAMF,GAiBR,oBAAZG,UACPA,QAAQtE,QAAUA,EAClBsE,QAAQJ,SAAWA,IAGnBnE,EAAOC,QAAUA,EACjBD,EAAOmE,SAAWA,EAEI,kBAAXK,SAAyBA,OAAOC,KACvCD,OAAO,WACH,OACIvE,QAASA,EACTkE,SAAUA,OAKT,mBAAXnE,QAAyB0E,KAAO1E"} \ No newline at end of file diff --git a/library/sprintf.js/gruntfile.js b/library/sprintf.js/gruntfile.js new file mode 100644 index 000000000..246e1c3b9 --- /dev/null +++ b/library/sprintf.js/gruntfile.js @@ -0,0 +1,36 @@ +module.exports = function(grunt) { + grunt.initConfig({ + pkg: grunt.file.readJSON("package.json"), + + uglify: { + options: { + banner: "/*! <%= pkg.name %> | <%= pkg.author %> | <%= pkg.license %> */\n", + sourceMap: true + }, + build: { + files: [ + { + src: "src/sprintf.js", + dest: "dist/sprintf.min.js" + }, + { + src: "src/angular-sprintf.js", + dest: "dist/angular-sprintf.min.js" + } + ] + } + }, + + watch: { + js: { + files: "src/*.js", + tasks: ["uglify"] + } + } + }) + + grunt.loadNpmTasks("grunt-contrib-uglify") + grunt.loadNpmTasks("grunt-contrib-watch") + + grunt.registerTask("default", ["uglify", "watch"]) +} diff --git a/library/sprintf.js/package.json b/library/sprintf.js/package.json new file mode 100644 index 000000000..ebf4a21fe --- /dev/null +++ b/library/sprintf.js/package.json @@ -0,0 +1,22 @@ +{ + "name": "sprintf-js", + "version": "1.0.2", + "description": "JavaScript sprintf implementation", + "author": "Alexandru Marasteanu (http://alexei.ro/)", + "main": "src/sprintf.js", + "scripts": { + "test": "mocha test/test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/alexei/sprintf.js.git" + }, + "license": "BSD-3-Clause", + "readmeFilename": "README.md", + "devDependencies": { + "mocha": "*", + "grunt": "*", + "grunt-contrib-watch": "*", + "grunt-contrib-uglify": "*" + } +} diff --git a/library/sprintf.js/src/angular-sprintf.js b/library/sprintf.js/src/angular-sprintf.js new file mode 100644 index 000000000..9c69123be --- /dev/null +++ b/library/sprintf.js/src/angular-sprintf.js @@ -0,0 +1,18 @@ +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") + }]) diff --git a/library/sprintf.js/src/sprintf.js b/library/sprintf.js/src/sprintf.js new file mode 100644 index 000000000..0ccb64c98 --- /dev/null +++ b/library/sprintf.js/src/sprintf.js @@ -0,0 +1,195 @@ +(function(window) { + var re = { + not_string: /[^s]/, + number: /[dief]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fiosuxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ + } + + function sprintf() { + var key = arguments[0], cache = sprintf.cache + if (!(cache[key] && cache.hasOwnProperty(key))) { + cache[key] = sprintf.parse(key) + } + return sprintf.format.call(null, cache[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 = "" + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]) + if (node_type === "string") { + output[output.length] = parse_tree[i] + } + else if (node_type === "array") { + 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 (get_type(arg) == "function") { + arg = arg() + } + + if (re.not_string.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { + throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) + } + + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } + + switch (match[8]) { + case "b": + arg = arg.toString(2) + break + case "c": + arg = String.fromCharCode(arg) + break + case "d": + case "i": + arg = parseInt(arg, 10) + break + case "e": + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() + break + case "f": + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case "o": + arg = arg.toString(8) + break + case "s": + arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) + break + case "u": + arg = arg >>> 0 + break + case "x": + arg = arg.toString(16) + break + case "X": + arg = arg.toString(16).toUpperCase() + break + } + 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 ? str_repeat(pad_character, pad_length) : "") : "" + output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) + } + } + return output.join("") + } + + sprintf.cache = {} + + sprintf.parse = function(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] + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = "%" + } + 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[field_list.length] = 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] + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = 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[parse_tree.length] = match + } + else { + throw new SyntaxError("[sprintf] unexpected placeholder") + } + _fmt = _fmt.substring(match[0].length) + } + return 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) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() + } + + function str_repeat(input, multiplier) { + return Array(multiplier + 1).join(input) + } + + /** + * export to either browser or node.js + */ + if (typeof exports !== "undefined") { + exports.sprintf = sprintf + exports.vsprintf = vsprintf + } + else { + window.sprintf = sprintf + window.vsprintf = vsprintf + + if (typeof define === "function" && define.amd) { + define(function() { + return { + sprintf: sprintf, + vsprintf: vsprintf + } + }) + } + } +})(typeof window === "undefined" ? this : window); diff --git a/library/sprintf.js/test/test.js b/library/sprintf.js/test/test.js new file mode 100644 index 000000000..1717d8fd0 --- /dev/null +++ b/library/sprintf.js/test/test.js @@ -0,0 +1,72 @@ +var assert = require("assert"), + sprintfjs = require("../src/sprintf.js"), + sprintf = sprintfjs.sprintf, + vsprintf = sprintfjs.vsprintf + +describe("sprintfjs", function() { + 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("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("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"})) + }) + + 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("-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")) + + // 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" })) + assert.equal(Date.now(), sprintf("%s", Date.now)) // should pass... + }) +}) -- cgit v1.2.3