A proposal to add String.prototype.format

Lasse Reichstein reichsteinatwork at gmail.com
Wed Mar 9 00:37:41 PST 2011


On Wed, 09 Mar 2011 01:21:09 +0100, Shanjian Li <shanjian at google.com>  
wrote:

> http://wiki.ecmascript.org/doku.php?id=strawman:string_format_take_two
>
> Please kindly review the proposal and let me know your feedback.

Just some nitpciking:

It doesn't specify how to print objects, except for %s, which says that if  
the argument is not
a string, convert it to string using .toString().
The string conversion should probably use the internal ToString function  
instead (which works for null
and undefined too).
For formats expecting numbers, it should convert the argument to a number  
using ToNumber.

Rounding is specified as "math.round(n - 0.5)" (capital M in Math?).
This leaves it open whether overwriting Math.round should change the  
behavior of format. It probably
shouldn't (i.e., again it would be better to specify in terms of internal,  
non-use-modifiable functions).
The rounding is equivalent to Math.floor(n) (aka round towards -Infinity),  
if I'm not mistaken, so why
not just use that?
(Personally I would prefer truncation (round towards zero), if conversion  
to integer is necessary).

Why can octal, binary and hexidecimal forms only be used on integers?  
Number.prototype.toString with
an argument works on fractions too (try Math.PI.toString(13) for laughs :).

Why only fixed bases (2,8,10,16)? How about adding an optional base  
parameter to number display (with
x, d, o, b as shorthands for the more standard bases)? Again,  
Number.prototype.toString means that it's
already in the language. (I know that step 7 says copy the format of other  
languages, but that seems
shortsighted since ECMAScript is not those languages, and only copying  
functionality from C verbatim
seems like tying your shoelaces together before the race).


"Placeholder used in format specifier part can not have format specifier.  
This prevent the replacement
 from embedding more than one level."
Should that be "... can not have a placeholder."?
If the placeholder value is not a string, it should be converted to a  
string.
If it is not a valid format, what happens then?


Is the following valid:
   "{x} and {1[y]}".format({x:42},{y:37})
I.e., can object property shorthands ({x} instead of {0[x]}) be used if  
there are more than one argument?


And some arbitrary ideas for extension:

How about a boolean test that checks for falsy-ness of the argument and  
acts as one of two other
formats or literals?
E.g.
   "{0:s} drew {1:?his|her} gun.".format(person.name, person.isMale)
   "Please press return{0:?.|{1}}".format(notCritical, " and run!")


Or allow computed indices?
   "{0[{1}][he]} drew {0[{1}][his]} gun.".format({male:{he:"He",his:"his"},  
female:{he:"She",his:"her"}}, "female");


/L
-- 
Lasse Reichstein - reichsteinatwork at gmail.com


More information about the es-discuss mailing list