[Pkg-javascript-commits] [node-sprintf-js] 02/08: Imported Upstream version 1.0.2

matthew pideil mpideil-guest at moszumanska.debian.org
Mon Mar 16 12:19:06 UTC 2015


This is an automated email from the git hooks/post-receive script.

mpideil-guest pushed a commit to branch master
in repository node-sprintf-js.

commit 165f82242513dc0e0e6844520714aca31b17f699
Author: Matthew Pideil <matthewp_debian at teledetection.fr>
Date:   Mon Mar 16 10:55:58 2015 +0100

    Imported Upstream version 1.0.2
---
 .gitignore                   |   1 +
 LICENSE                      |  24 ++++++
 README.md                    |  82 ++++++++++++++++++
 bower.json                   |  14 ++++
 debian/changelog             |   6 --
 debian/compat                |   1 -
 debian/control               |  24 ------
 debian/copyright             |  38 ---------
 debian/docs                  |   1 -
 debian/install               |   1 -
 debian/rules                 |  15 ----
 debian/source/format         |   1 -
 debian/tests/control         |   2 -
 debian/tests/require         |   3 -
 debian/watch                 |   5 --
 demo/angular.html            |  20 +++++
 dist/angular-sprintf.min.js  |   4 +
 dist/angular-sprintf.min.map |   1 +
 dist/sprintf.min.js          |   4 +
 dist/sprintf.min.map         |   1 +
 gruntfile.js                 |  36 ++++++++
 package.json                 |  22 +++++
 src/angular-sprintf.js       |  18 ++++
 src/sprintf.js               | 195 +++++++++++++++++++++++++++++++++++++++++++
 test/test.js                 |  72 ++++++++++++++++
 25 files changed, 494 insertions(+), 97 deletions(-)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..096746c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/node_modules/
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..5c74c82
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,24 @@
+Copyright (c) 2007-2013, Alexandru Marasteanu <hello [at) alexei (dot] ro>
+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/README.md b/README.md
new file mode 100644
index 0000000..d4c7203
--- /dev/null
+++ b/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/bower.json b/bower.json
new file mode 100644
index 0000000..ecdf6d5
--- /dev/null
+++ b/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 <hello at alexei.ro> (http://alexei.ro/)"],
+  "homepage": "https://github.com/alexei/sprintf.js",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/alexei/sprintf.js.git"
+  }
+}
diff --git a/debian/changelog b/debian/changelog
deleted file mode 100644
index 5320121..0000000
--- a/debian/changelog
+++ /dev/null
@@ -1,6 +0,0 @@
-node-sprintf-js (1.0.2-1) UNRELEASED; urgency=low
-
-  * Initial release (Closes: #nnnn)
-
- -- Matthew Pideil <matthewp_debian at teledetection.fr>  Mon, 16 Mar 2015 10:36:14 +0100
-
diff --git a/debian/compat b/debian/compat
deleted file mode 100644
index 45a4fb7..0000000
--- a/debian/compat
+++ /dev/null
@@ -1 +0,0 @@
-8
diff --git a/debian/control b/debian/control
deleted file mode 100644
index e859e28..0000000
--- a/debian/control
+++ /dev/null
@@ -1,24 +0,0 @@
-Source: node-sprintf-js
-Section: web
-Priority: extra
-Maintainer: Debian Javascript Maintainers <pkg-javascript-devel at lists.alioth.debian.org>
-Uploaders: Matthew Pideil <matthewp_debian at teledetection.fr>
-Build-Depends:
- debhelper (>= 8)
- , dh-buildinfo
- , nodejs
-Standards-Version: 3.9.6
-Homepage: https://github.com/alexei/sprintf.js
-Vcs-Git: git://anonscm.debian.org/pkg-javascript/node-sprintf-js.git
-Vcs-Browser: http://anonscm.debian.org/gitweb/?p=pkg-javascript/node-sprintf-js.git
-XS-Testsuite: autopkgtest
-
-Package: node-sprintf-js
-Architecture: all
-Depends:
- ${misc:Depends}
- , nodejs
-Description: JavaScript sprintf implementation
- FIX_ME long description
- .
- Node.js is an event-based server-side JavaScript engine.
diff --git a/debian/copyright b/debian/copyright
deleted file mode 100644
index 328bfdd..0000000
--- a/debian/copyright
+++ /dev/null
@@ -1,38 +0,0 @@
-Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
-Upstream-Name: sprintf-js
-Upstream-Contact: https://github.com/alexei/sprintf.js/issues
-Source: https://github.com/alexei/sprintf.js
-
-Files: *
-Copyright: 2015 Alexandru Marasteanu <hello at alexei.ro> (http://alexei.ro/)
-License: BSD-3-Clause
-
-Files: debian/*
-Copyright: 2015 Matthew Pideil <matthewp_debian at teledetection.fr>
-License: BSD-3-Clause
-
-License: BSD-3-clause
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
-    notice, this list of conditions and the following disclaimer.
- 2. 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.
- 3. Neither the name of the University 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 HOLDERS OR
- CONTRIBUTORS 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/debian/docs b/debian/docs
deleted file mode 100644
index b43bf86..0000000
--- a/debian/docs
+++ /dev/null
@@ -1 +0,0 @@
-README.md
diff --git a/debian/install b/debian/install
deleted file mode 100644
index 88c8ff7..0000000
--- a/debian/install
+++ /dev/null
@@ -1 +0,0 @@
-package.json usr/lib/nodejs/sprintf-js/
diff --git a/debian/rules b/debian/rules
deleted file mode 100755
index de57af0..0000000
--- a/debian/rules
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/usr/bin/make -f
-# -*- makefile -*-
-
-# Uncomment this to turn on verbose mode.
-#export DH_VERBOSE=1
-
-%:
-	dh $@
-
-#override_dh_auto_build:
-
-#override_dh_auto_test:
-
-
-
diff --git a/debian/source/format b/debian/source/format
deleted file mode 100644
index 163aaf8..0000000
--- a/debian/source/format
+++ /dev/null
@@ -1 +0,0 @@
-3.0 (quilt)
diff --git a/debian/tests/control b/debian/tests/control
deleted file mode 100644
index 25fd591..0000000
--- a/debian/tests/control
+++ /dev/null
@@ -1,2 +0,0 @@
-Tests: require
-Depends: node-sprintf-js
diff --git a/debian/tests/require b/debian/tests/require
deleted file mode 100644
index edc4ae3..0000000
--- a/debian/tests/require
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/sh
-set -e
-nodejs -e "require('sprintf-js');"
diff --git a/debian/watch b/debian/watch
deleted file mode 100644
index f022ddb..0000000
--- a/debian/watch
+++ /dev/null
@@ -1,5 +0,0 @@
-version=3
-opts=\
-dversionmangle=s/\+(debian|dfsg|ds|deb)(\.\d+)?$//,\
-filenamemangle=s/.*\/v?([\d\.-]+)\.tar\.gz/node-sprintf-js-$1.tar.gz/ \
- https://github.com/alexei/sprintf.js/tags .*/archive/v?([\d\.]+).tar.gz
diff --git a/demo/angular.html b/demo/angular.html
new file mode 100644
index 0000000..3559efd
--- /dev/null
+++ b/demo/angular.html
@@ -0,0 +1,20 @@
+<!doctype html>
+<html ng-app="app">
+<head>
+    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.min.js"></script>
+    <script src="../src/sprintf.js"></script>
+    <script src="../src/angular-sprintf.js"></script>
+</head>
+<body>
+    <pre>{{ "%+010d"|sprintf:-123 }}</pre>
+    <pre>{{ "%+010d"|vsprintf:[-123] }}</pre>
+    <pre>{{ "%+010d"|fmt:-123 }}</pre>
+    <pre>{{ "%+010d"|vfmt:[-123] }}</pre>
+    <pre>{{ "I've got %2$d apples and %1$d oranges."|fmt:4:2 }}</pre>
+    <pre>{{ "I've got %(apples)d apples and %(oranges)d oranges."|fmt:{apples: 2, oranges: 4} }}</pre>
+
+    <script>
+        angular.module("app", ["sprintf"])
+    </script>
+</body>
+</html>
diff --git a/dist/angular-sprintf.min.js b/dist/angular-sprintf.min.js
new file mode 100644
index 0000000..dbaf744
--- /dev/null
+++ b/dist/angular-sprintf.min.js
@@ -0,0 +1,4 @@
+/*! sprintf-js | Alexandru Marasteanu <hello at alexei.ro> (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/dist/angular-sprintf.min.map b/dist/angular-sprintf.min.map
new file mode 100644
index 0000000..055964c
--- /dev/null
+++ b/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/dist/sprintf.min.js b/dist/sprintf.min.js
new file mode 100644
index 0000000..d5bcd09
--- /dev/null
+++ b/dist/sprintf.min.js
@@ -0,0 +1,4 @@
+/*! sprintf-js | Alexandru Marasteanu <hello at alexei.ro> (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- [...]
+//# sourceMappingURL=sprintf.min.map
\ No newline at end of file
diff --git a/dist/sprintf.min.map b/dist/sprintf.min.map
new file mode 100644
index 0000000..33fe163
--- /dev/null
+++ b/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","n [...]
\ No newline at end of file
diff --git a/gruntfile.js b/gruntfile.js
new file mode 100644
index 0000000..246e1c3
--- /dev/null
+++ b/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/package.json b/package.json
new file mode 100644
index 0000000..ebf4a21
--- /dev/null
+++ b/package.json
@@ -0,0 +1,22 @@
+{
+    "name": "sprintf-js",
+    "version": "1.0.2",
+    "description": "JavaScript sprintf implementation",
+    "author": "Alexandru Marasteanu <hello at alexei.ro> (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/src/angular-sprintf.js b/src/angular-sprintf.js
new file mode 100644
index 0000000..9c69123
--- /dev/null
+++ b/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/src/sprintf.js b/src/sprintf.js
new file mode 100644
index 0000000..0ccb64c
--- /dev/null
+++ b/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/test/test.js b/test/test.js
new file mode 100644
index 0000000..1717d8f
--- /dev/null
+++ b/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...
+    })
+})

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-sprintf-js.git



More information about the Pkg-javascript-commits mailing list