Skip to content

Commit

Permalink
Adds type option
Browse files Browse the repository at this point in the history
  • Loading branch information
alexei committed Jan 2, 2016
1 parent 242eef8 commit c31c24e
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 5 deletions.
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -25,10 +25,13 @@ The placeholders in the format string are marked by `%` and are followed by one
* `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 argument<sup>[1](#fn1)</sup>
* `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

<a name="fn1">1</a> `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.

## JavaScript `vsprintf`
`vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments:

Expand Down
2 changes: 1 addition & 1 deletion dist/sprintf.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/sprintf.min.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 9 additions & 3 deletions src/sprintf.js
Expand Up @@ -2,12 +2,14 @@
var re = {
not_string: /[^s]/,
not_bool: /[^t]/,
not_type: /[^T]/,
number: /[diefg]/,
numeric_arg: /bcdiefguxX/,
json: /[j]/,
not_json: /[^j]/,
text: /^[^\x25]+/,
modulo: /^\x25{2}/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostuxX])/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuxX])/,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/i,
index_access: /^\[(\d+)\]/,
Expand Down Expand Up @@ -47,11 +49,11 @@
arg = argv[cursor++]
}

if (get_type(arg) == 'function') {
if (re.not_type.test(match[8]) && get_type(arg) == 'function') {
arg = arg()
}

if (re.not_string.test(match[8]) && re.not_bool.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != 'number' && isNaN(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)))
}

Expand Down Expand Up @@ -92,6 +94,10 @@
arg = String(!!arg)
arg = (match[6] ? arg.substring(0, match[6]) : arg)
break
case 'T':
arg = get_type(arg)
arg = (match[6] ? arg.substring(0, match[6]) : arg)
break
case 'u':
arg = parseInt(arg, 10) >>> 0
break
Expand Down

0 comments on commit c31c24e

Please sign in to comment.