Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #14608 > unrolled thread

Placing 'zeros' in front of a number ?

Started by"Mel Smith" <med_cutout_syntel@aol.com>
First post2012-06-21 18:37 -0600
Last post2012-06-23 20:00 +0100
Articles 20 on this page of 26 — 10 participants

Back to article view | Back to comp.lang.javascript


Contents

  Placing 'zeros' in front of a number ? "Mel Smith" <med_cutout_syntel@aol.com> - 2012-06-21 18:37 -0600
    Re: Placing 'zeros' in front of a number ? Gene Wirchenko <genew@ocis.net> - 2012-06-21 18:59 -0700
    Re: Placing 'zeros' in front of a number ? "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2012-06-21 20:18 -0700
      Re: Placing 'zeros' in front of a number ? "Mel Smith" <med_cutout_syntel@aol.com> - 2012-06-21 22:51 -0600
      Re: Placing 'zeros' in front of a number ? Gregor Kofler <usenet@gregorkofler.com> - 2012-06-22 10:34 +0200
        Re: Placing 'zeros' in front of a number ? Scott Sauyet <scott.sauyet@gmail.com> - 2012-06-22 04:49 -0700
          Re: Placing 'zeros' in front of a number ? "Mel Smith" <med_cutout_syntel@aol.com> - 2012-06-22 08:39 -0600
          Re: Placing 'zeros' in front of a number ? "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2012-06-22 13:05 -0700
          Re: Placing 'zeros' in front of a number ? Gene Wirchenko <genew@ocis.net> - 2012-06-22 14:10 -0700
        Re: Placing 'zeros' in front of a number ? "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2012-06-22 22:58 +0000
          Re: Placing 'zeros' in front of a number ? Hans-Georg Michna <hans-georgNoEmailPlease@michna.com> - 2012-06-23 18:47 +0200
            Re: Placing 'zeros' in front of a number ? "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2012-06-23 21:44 +0000
              Re: Placing 'zeros' in front of a number ? "Mel Smith" <med_cutout_syntel@aol.com> - 2012-06-23 16:48 -0600
          Re: Placing 'zeros' in front of a number ? "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2012-06-23 16:56 -0700
        Re: Placing 'zeros' in front of a number ? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-06-23 19:47 +0200
          Re: Placing 'zeros' in front of a number ? Gregor Kofler <usenet@gregorkofler.com> - 2012-06-23 20:52 +0200
            Re: Placing 'zeros' in front of a number ? Gregor Kofler <usenet@gregorkofler.com> - 2012-06-23 21:01 +0200
          Re: Placing 'zeros' in front of a number ? "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2012-06-23 17:05 -0700
            Re: Placing 'zeros' in front of a number ? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-06-24 03:51 +0200
              Re: Placing 'zeros' in front of a number ? "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2012-06-25 20:19 -0700
                Re: Placing 'zeros' in front of a number ? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-06-26 09:04 +0200
                  Re: Placing 'zeros' in front of a number ? "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2012-06-26 08:32 -0700
                    Re: Placing 'zeros' in front of a number ? Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2012-06-26 22:12 +0200
                      Re: Placing 'zeros' in front of a number ? "Michael Haufe (TNO)" <tno@thenewobjective.com> - 2012-06-30 13:41 -0700
                Re: Placing 'zeros' in front of a number ? Dr J R Stockton <reply1226@merlyn.demon.co.uk.not.invalid> - 2012-06-27 19:34 +0100
    Re: Placing 'zeros' in front of a number ? Dr J R Stockton <reply1225@merlyn.demon.co.uk.not.invalid> - 2012-06-23 20:00 +0100

Page 1 of 2  [1] 2  Next page →


#14608 — Placing 'zeros' in front of a number ?

From"Mel Smith" <med_cutout_syntel@aol.com>
Date2012-06-21 18:37 -0600
SubjectPlacing 'zeros' in front of a number ?
Message-ID<a4ht2oFf7iU1@mid.individual.net>
Hi:

    I've got a bunch of numbers (in string format), that I want to convert 
to strings of a standard length of four characters:

    e.g.,    '1'     >>> '0001'
             '10'    >>> '0010'
           '123'    >>> '0123'
           '4567'  >>> '4567'    // leave as is for length of 4

    I would like a general javascript function to convert the strings on the 
left above to those on the right --  for a variety of widths.

    I do this now but in an embarassingly slow and clumsy way.

    In my native language (Harbour), we have a function called strzero() 
which is used something like this:

        cMyStringifiedNumber = "123"
        cMyNewStringifiednumber := STRZERO(val(cMyStringifiedNumber),4,0)
        // the val() function converts a string to a number
        // then the strzero() function operates on the number and returns a 
new stringified number

        // and where the '4' indicates the total width of the needed string
        // and the the ',0' meand no decimal points needed in the result.

        // the result for the above is '0123'
        //. that is, a '0' is placed at the front of the string

    Has anybody got a generalized function that can do the above please ??

Thank you !
-- 
Mel Smith

[toc] | [next] | [standalone]


#14610

FromGene Wirchenko <genew@ocis.net>
Date2012-06-21 18:59 -0700
Message-ID<r3k7u71mrdpmfngna9uu8amvd043gcobjs@4ax.com>
In reply to#14608
On Thu, 21 Jun 2012 18:37:43 -0600, "Mel Smith"
<med_cutout_syntel@aol.com> wrote:

[snip]

>    Has anybody got a generalized function that can do the above please ??

     The following works on strings not numbers, but you can adjust to
suit.  The key bit of code that you want is the final return
statement.  That trick with Array.join() generates a string of n
characters.  (Note that the argument to Array() should be n+1.)  For
your example, you would call as in
          var Padded=PadL("123",4,"0");

***** Start of Code *****
// PadL()
// Pad String on Left
// Last Modification: 2012-01-12
// This function will trim to the length as well.

function PadL
 (
 theString,     // string: the value to pad
 Length,        // int: how long to pad to
 theChar        // string (one character): the character to pad with
 )
  {
  if (theChar.length!=1)     // If bad character...
    return theString;        // ...do nothing to string.
  if (theString.length>Length)     // trim?
    return theString.substr(0,Length);
  return Array(Length-theString.length+1).join(theChar)+theString;
  }
***** End of Code *****

Sincerely,

Gene Wirchenko

[toc] | [prev] | [next] | [standalone]


#14611

From"Michael Haufe (TNO)" <tno@thenewobjective.com>
Date2012-06-21 20:18 -0700
Message-ID<68f86607-2127-46c8-b59d-a0b010335f32@googlegroups.com>
In reply to#14608
On Thursday, June 21, 2012 7:37:43 PM UTC-5, Mel Smith wrote:
[...]
>     I've got a bunch of numbers (in string format), that I want to convert 
> to strings of a standard length of four characters:
> 
>     e.g.,    '1'     >>> '0001'
>              '10'    >>> '0010'
>            '123'    >>> '0123'
>            '4567'  >>> '4567'    // leave as is for length of 4
[...]

Perhaps something like this:

String.prototype.padLeft = function(ch,len){
    return Array(Math.max(0, len - this.length + 1)).join(ch) + this;
}

'1'.padLeft('0',4);
'10'.padLeft('0',4);
'123'.padLeft('0',4);
'4567'.padLeft('0',4);

[toc] | [prev] | [next] | [standalone]


#14613

From"Mel Smith" <med_cutout_syntel@aol.com>
Date2012-06-21 22:51 -0600
Message-ID<a4ibuuFcs7U1@mid.individual.net>
In reply to#14611
Gene & Michael:

    Thank you for your offerings !

    I'll try them both tomorrow.

-Mel

[toc] | [prev] | [next] | [standalone]


#14614

FromGregor Kofler <usenet@gregorkofler.com>
Date2012-06-22 10:34 +0200
Message-ID<js1amg$mv1$1@dont-email.me>
In reply to#14611
Am 2012-06-22 05:18, Michael Haufe (TNO) meinte:
> On Thursday, June 21, 2012 7:37:43 PM UTC-5, Mel Smith wrote:
> [...]
>>      I've got a bunch of numbers (in string format), that I want to convert
>> to strings of a standard length of four characters:
>>
>>      e.g.,    '1'     >>> '0001'
>>               '10'    >>> '0010'
>>             '123'    >>> '0123'
>>             '4567'  >>> '4567'    // leave as is for length of 4
> [...]
>
> Perhaps something like this:
>
> String.prototype.padLeft = function(ch,len){
>      return Array(Math.max(0, len - this.length + 1)).join(ch) + this;
> }

Or

String.prototype.lpad = function(len, fchar) {
   var i = len-this.length, pad = "", f = fchar || " ";
   while(i--) { pad += f; }
   return pad+this;
};

In a completely un-scientific benchmark in Firefox and Chromium this 
solution is about twice as fast (the difference becomes less with very 
long paddings). In any case I would change your order of arguments since 
"len" is in any case a required argument, whereas "ch" can be set to a 
default value.

Gregor

[toc] | [prev] | [next] | [standalone]


#14615

FromScott Sauyet <scott.sauyet@gmail.com>
Date2012-06-22 04:49 -0700
Message-ID<3542fb54-c108-4730-abd5-07a4192654b2@t20g2000yqn.googlegroups.com>
In reply to#14614
Gregor Kofler wrote:
> Michael Haufe (TNO) meinte:
>> Mel Smith wrote:
>> [...]
>>>      I've got a bunch of numbers (in string format), that I want to convert
>>> to strings of a standard length of four characters:
>> [...]
>
>> String.prototype.padLeft = function(ch,len){
>>      return Array(Math.max(0, len - this.length + 1)).join(ch) + this;
>> }
>
> Or
>
> String.prototype.lpad = function(len, fchar) {
>    var i = len-this.length, pad = "", f = fchar || " ";
>    while(i--) { pad += f; }
>    return pad+this;
> };
>
> In a completely un-scientific benchmark in Firefox and Chromium this
> solution is about twice as fast (the difference becomes less with very
> long paddings).

Someone published jsperf tests recently on this:

    <http://jsperf.com/ways-to-0-pad-a-number/10>

The Array.join method is significantly slower than all other
techniques shown in all JS engines tested.


> In any case I would change your order of arguments since
> "len" is in any case a required argument, whereas "ch" can be set to a
> default value.

Agreed, although I would offer defaults for both of them.

  -- Scott

[toc] | [prev] | [next] | [standalone]


#14616

From"Mel Smith" <med_cutout_syntel@aol.com>
Date2012-06-22 08:39 -0600
Message-ID<a4jecdFdsjU1@mid.individual.net>
In reply to#14615
    <http://jsperf.com/ways-to-0-pad-a-number/10>

The Array.join method is significantly slower than all other
techniques shown in all JS engines tested.


> In any case I would change your order of arguments since
> "len" is in any case a required argument, whereas "ch" can be set to a
> default value.

Agreed, although I would offer defaults for both of them.


Gregor & Scott:


    Several good choices.   I'll pick and test one today.

Thanks all !

-Mel Smith

[toc] | [prev] | [next] | [standalone]


#14618

From"Michael Haufe (TNO)" <tno@thenewobjective.com>
Date2012-06-22 13:05 -0700
Message-ID<597e1d45-3686-4465-890f-aaffead1ab2b@googlegroups.com>
In reply to#14615
On Friday, June 22, 2012 6:49:06 AM UTC-5, Scott Sauyet wrote:
> Someone published jsperf tests recently on this:
> 
>     <http://jsperf.com/ways-to-0-pad-a-number/10>
> 
> The Array.join method is significantly slower than all other
> techniques shown in all JS engines tested.

I just added a recursive version:

    <http://jsperf.com/ways-to-0-pad-a-number/11>

[toc] | [prev] | [next] | [standalone]


#14619

FromGene Wirchenko <genew@ocis.net>
Date2012-06-22 14:10 -0700
Message-ID<fen9u7tfg1emuc48rpjquepmoufj94kti4@4ax.com>
In reply to#14615
On Fri, 22 Jun 2012 04:49:06 -0700 (PDT), Scott Sauyet
<scott.sauyet@gmail.com> wrote:

[snip]

>Someone published jsperf tests recently on this:
>
>    <http://jsperf.com/ways-to-0-pad-a-number/10>
>
>The Array.join method is significantly slower than all other
>techniques shown in all JS engines tested.

     Part of this is that the code generates too long of a string and
then left-truncates it.

     A sensible implementation would stringize the number and then
prepend the number of "0"s needed.  I do not know if this would make
it significantly faster.

     There has been no specification for how to handle a negative
number.  A quick look at the code suggests that none of the methods at
the URL will work for negative numbers.  Mine will not either.  (By
"work", I mean to keep the digits together, as in -12345 padded to
eight characters should give "-0012345" not "00-12345".)

[snip]

Sincerely,

Gene Wirchenko

[toc] | [prev] | [next] | [standalone]


#14620

From"Evertjan." <exxjxw.hannivoort@inter.nl.net>
Date2012-06-22 22:58 +0000
Message-ID<XnsA07B9EF4674Eeejj99@194.109.133.133>
In reply to#14614
Gregor Kofler wrote on 22 jun 2012 in comp.lang.javascript:

> String.prototype.lpad = function(len, fchar) {
>    var i = len-this.length, pad = "", f = fchar || " ";
>    while(i--) { pad += f; }
>    return pad+this;
>};
> 

function pad(v,n) {
   if ((v+'').length>n) return v;
   return ('00000000'+v).substr(-n);
};

alert( pad(15,5) ); // 00015

alert( pad(15,1) ); // 15


-- 
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

[toc] | [prev] | [next] | [standalone]


#14624

FromHans-Georg Michna <hans-georgNoEmailPlease@michna.com>
Date2012-06-23 18:47 +0200
Message-ID<pksbu7dhkqp9ocuiibtjpopnv1npvh8uhf@4ax.com>
In reply to#14620
On 22 Jun 2012 22:58:37 GMT, Evertjan. wrote:

>Gregor Kofler wrote on 22 jun 2012 in comp.lang.javascript:

>> String.prototype.lpad = function(len, fchar) {
>>    var i = len-this.length, pad = "", f = fchar || " ";
>>    while(i--) { pad += f; }
>>    return pad+this;
>>};

>function pad(v,n) {
>   if ((v+'').length>n) return v;
>   return ('00000000'+v).substr(-n);
>};
>
>alert( pad(15,5) ); // 00015
>
>alert( pad(15,1) ); // 15

Thanks for providing this. If you hadn't, I would have, because
some of the other solutions provided earlier are needlessly
complicated.

In this particular case, assuming that there are only positive
numbers not bigger than 9999 the simple expression

("000" + number).substr(-4)

already does the trick.

Hans-Georg

[toc] | [prev] | [next] | [standalone]


#14632

From"Evertjan." <exxjxw.hannivoort@inter.nl.net>
Date2012-06-23 21:44 +0000
Message-ID<XnsA07BF172DA083eejj99@194.109.133.133>
In reply to#14624
Hans-Georg Michna wrote on 23 jun 2012 in comp.lang.javascript:

> In this particular case, assuming that there are only positive
> numbers not bigger than 9999 the simple expression
> 
> ("000" + number).substr(-4)
> 
> already does the trick.

Next to the above contacanating solution,
here the equivalent numeric addition solution:

( 60000 + number ).toString().substr(-4)

or even

( 70000 + 15 + '' ).substr(-4)

-- 
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

[toc] | [prev] | [next] | [standalone]


#14636

From"Mel Smith" <med_cutout_syntel@aol.com>
Date2012-06-23 16:48 -0600
Message-ID<a4mvd6F241U1@mid.individual.net>
In reply to#14632
Evertjan said:

>> ("000" + number).substr(-4)
>>
>> already does the trick.
>
> Next to the above contacanating solution,
> here the equivalent numeric addition solution:
>
> ( 60000 + number ).toString().substr(-4)
>
> or even
>
> ( 70000 + 15 + '' ).substr(-4)


Evertjan:

    Thank you for this simple solution to my problem !

-Mel Smith

[toc] | [prev] | [next] | [standalone]


#14638

From"Michael Haufe (TNO)" <tno@thenewobjective.com>
Date2012-06-23 16:56 -0700
Message-ID<f618b0b6-0904-4881-80cf-9c425b72d2cc@googlegroups.com>
In reply to#14620
On Friday, June 22, 2012 5:58:37 PM UTC-5, Evertjan. wrote:
> function pad(v,n) {
>    if ((v+'').length>n) return v;
>    return ('00000000'+v).substr(-n);
> };

I don't see the value in hard coding the padded character.

[toc] | [prev] | [next] | [standalone]


#14625

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2012-06-23 19:47 +0200
Message-ID<1623778.oMNUckLgyt@PointedEars.de>
In reply to#14614
Gregor Kofler wrote:

> Am 2012-06-22 05:18, Michael Haufe (TNO) meinte:
>> On Thursday, June 21, 2012 7:37:43 PM UTC-5, Mel Smith wrote:
>> [...]
>>>      I've got a bunch of numbers (in string format), that I want to
>>>      convert
>>> to strings of a standard length of four characters:
>>>
>>>      e.g.,    '1'     >>> '0001'
>>>               '10'    >>> '0010'
>>>             '123'    >>> '0123'
>>>             '4567'  >>> '4567'    // leave as is for length of 4
>> [...]
>>
>> Perhaps something like this:
>>
>> String.prototype.padLeft = function(ch,len){
>>      return Array(Math.max(0, len - this.length + 1)).join(ch) + this;
>> }
> 
> Or
> 
> String.prototype.lpad = function(len, fchar) {
>    var i = len-this.length, pad = "", f = fchar || " ";
>    while(i--) { pad += f; }
>    return pad+this;
> };
> 
> In a completely un-scientific benchmark in Firefox and Chromium this 
> solution is about twice as fast (the difference becomes less with very 
> long paddings). In any case I would change your order of arguments since 
> "len" is in any case a required argument, whereas "ch" can be set to a 
> default value.

Having reviewed these two solutions (see below), I still prefer mine (in 
JSX:string.js@244):

/**
 * Non-breaking space
 */
var CH_NBSP = "\xA0";

/**
 * @param s : optional string
 *   Input string.  If omitted and the calling object
 *   is a String object, it is used instead.
 * @param n : optional number = 1
 *   Length of the resulting string.  The default is 1,
 *   i.e. if the input string is empty, "0" is returned
 *   if c is <code>'0'</code>.
 * @param c : optional string = CH_NBSP
 *   Character string to use for padding.  The default
 *   is one non-breaking space.
 * @param bRight : optional boolean = false
 *   If <code>true</code>, s is padded on the right,
 *   otherwise on the left.
 * @param iStart : optional number
 *   Assume that s is iStart characters long.
 * @return string
 *   The padded input string so that its length is n.
 */
var pad = jsx.string.pad = function(s, n, c, bRight, iStart) {
  var constr;
  if ((constr = this.constructor) && constr == String
      && typeof s != "string")
  {
    s = this;
  }
  
  if (!n)
  {
    n = 1;
  }
  
  if (!c)
  {
    c = CH_NBSP;
  }
  
  if (typeof s != "string")
  {
    s = String(s);
  }
  
  if (typeof iStart == "undefined")
  {
    iStart = s.length;
  }
  
  if (n <= iStart)
  {
    return s;
  }
  
  var a = [];
  var missingLength = n - iStart + 1;
  
  if (typeof a.join == "function"
      && (missingLength > -1) && (missingLength < Math.pow(2, 32)))
  {
    a.length = missingLength;
    var rep = a.join(c);
    if (bRight)
    {
      s += rep;
    }
    else
    {
      s = rep + s;
    }
  }
  else
  {
    while (iStart < n)
    {
      if (bRight)
      {
        s += c;
      }
      else
      {
        s = c + s;
      }
  
      iStart++;
    }
  }

  return s;
};  

for which there is

/**
 * @param s : optional string
 *   Input string.  If omitted and the calling object
 *   is a String object, it is used instead.
 * @param n : optional number
 *   Length of the resulting string.  The default is 1,
 *   i.e. if the input string is empty, "0" is returned.
 * @return string
 *   Input string with leading zeros so that
 *   its length is @{(n)}.
 * @see
 *   #pad(string, number, string)
 */
function leadingZero(s, n)
{
  var c;
  if ((c = this.constructor) && c == String && typeof s != "string")
  {
    s = this;
  }
   
  return pad(s, n, "0");
}

here.

jsx.string.pad() being used by leadingZero() scores over the two solutions 
above in several respects:

- It can be, but does not have to be, transferred to String instances or
  String prototypes for use as a method (one might even consider using
  `instanceof' now in case someone wants to inherit from String.prototype). 
  This makes it directly applicable to non-string values.  Both solutions
  above can only be used with objects inheriting from String.prototype.

- It does not pad if there is nothing to pad.  Both solutions above do that.

- It has no dependency on the run-time values of `Array' and `Math.max',
  so overwriting those properties should not be able to stop it from
  working.  Michael's solution depends on both.

- It minimizes method calls, which are expensive.  Michael's solution uses
  several method calls.  Gregor's uses none, but at the price of repeated
  non-native string concatenation when not necessary.

- It avoids repetitive non-native concatenation, which is expensive with
  long strings.  Michael's solution avoids that too, but at the price
  of not being able to work with len > Math.pow(2, 32) - 1.

- It works efficiently with len smaller than or equal to
  Math.pow(2, 32) - 1, but also works with greater values.

- It can handle awkward values.  Gregor's solution hangs in an endless loop
  when passed a len < this.length.  Michael's handles that problem with
  Math.max().

- It can handle literal 0 (any convertible false-value, really) as pad
  value.  Gregor's solution would default to a space character then.

- It pads with one *non-breaking* space by default.  With Michael's
  you have to be explicit, Gregor's defaults to a space.

- It is backwards-compatible to a large degree:

  + It uses a loop where is no Array.prototype.join() or the padding
    length does not fit.  

  + It does not depend on a single numeric argument to `Array' designating
    the array length.  This was a concern with earlier JavaScript versions –
    but then again those versions also did not support the Array initializer
    that I am using now.  I am not aware of other implementations copying
    the non-conforming behavior, although there may be some.

  Michael's solution is not backwards-compatible.  Gregor's is more
  backwards-compatible than mine, but at the price of insufficient
  fallbacks and reduced speed in the worst case.

- It can pad either left or right which makes it useful for an sprintf()
  implementation.  The solutions above require an extra implementation
  for padding right-hand side.

- It is not depend on the string length of the value to be padded.
  Apparently sometimes it is useful to let the string length of a value
  appear longer or shorter than it actually is (I do not remember the
  use-case right now, but I am sure there was one).  You can pass a value
  for iStart (don't ask) to tell jsx.string.pad() that the actual string
  length does not matter.

Constructive comments and suggestions are welcome.  (I know it still spoils 
the global namespace a bit.  This will be fixed but is kept until depending 
code has been fixed.)

However: All our solutions fail to achieve properly left-padding string 
representations of negative numbers.  (Since fixing that would require yet 
another parameter for jsx.string.pad() – to keep it general –, perhaps it is 
time now to support a second `options' parameter; whenever it is not a 
number, try accessing the properties of the referred object for options.)


PointedEars
-- 
var bugRiddenCrashPronePieceOfJunk = (
    navigator.userAgent.indexOf('MSIE 5') != -1
    && navigator.userAgent.indexOf('Mac') != -1
)  // Plone, register_function.js:16

[toc] | [prev] | [next] | [standalone]


#14627

FromGregor Kofler <usenet@gregorkofler.com>
Date2012-06-23 20:52 +0200
Message-ID<js539k$sbd$1@dont-email.me>
In reply to#14625
Am 2012-06-23 19:47, Thomas 'PointedEars' Lahn meinte:

[snip]

> - It can handle awkward values.  Gregor's solution hangs in an endless loop
>    when passed a len < this.length.  Michael's handles that problem with
>    Math.max().
>
> - It can handle literal 0 (any convertible false-value, really) as pad
>    value.  Gregor's solution would default to a space character then.

Thanks for pointing out. Particularly the first one could be nasty.

Gregor

[toc] | [prev] | [next] | [standalone]


#14628

FromGregor Kofler <usenet@gregorkofler.com>
Date2012-06-23 21:01 +0200
Message-ID<js53qk$vrm$1@dont-email.me>
In reply to#14627
Am 2012-06-23 20:52, Gregor Kofler meinte:
> Am 2012-06-23 19:47, Thomas 'PointedEars' Lahn meinte:
>
> [snip]
>
>> - It can handle awkward values.  Gregor's solution hangs in an endless
>> loop
>>    when passed a len < this.length.  Michael's handles that problem with
>>    Math.max().
>>
>> - It can handle literal 0 (any convertible false-value, really) as pad
>>    value.  Gregor's solution would default to a space character then.
>
> Thanks for pointing out. Particularly the first one could be nasty.

I just checked my "original" script, it always had a

while(--i >= 0) { ... } loop. (The latter issue is remains.)

Gregor

[toc] | [prev] | [next] | [standalone]


#14639

From"Michael Haufe (TNO)" <tno@thenewobjective.com>
Date2012-06-23 17:05 -0700
Message-ID<b8fc4748-4126-46c4-958e-55c8462ec5ca@googlegroups.com>
In reply to#14625
On Saturday, June 23, 2012 12:47:22 PM UTC-5, Thomas &#39;PointedEars&#39; Lahn wrote:

> Having reviewed these two solutions (see below), I still prefer mine...

I would have preferred my second solution mentioned to be evaluated, which was added to the jsperf website:

---

function padLeft(str, ch, len){
    return str.length >= len ? str : padLeft(ch + str, ch, len);
}

---

<http://jsperf.com/ways-to-0-pad-a-number/11>

[toc] | [prev] | [next] | [standalone]


#14641

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2012-06-24 03:51 +0200
Message-ID<11390067.YXlMqVrOKe@PointedEars.de>
In reply to#14639
Michael Haufe (TNO) wrote:

> Thomas &#39;PointedEars&#39; Lahn wrote:
>> Having reviewed these two solutions (see below), I still prefer mine...
> 
> I would have preferred my second solution mentioned to be evaluated, which
> was added to the jsperf website:

The disadvantage of Google Groups postings to the interested poster is that 
I do not see them (which is an advantage to me in most other cases), except 
when they are followups to my postings and the poster was not killfiled.  
Since I am not alone in this, I strongly suggest you switch to a more 
responsible Usenet access provider.
 
> function padLeft(str, ch, len){
>     return str.length >= len ? str : padLeft(ch + str, ch, len);
> }

I do not think this recursive solution is very efficient or compatible 
either.  Instead of a fixed number of 2 function calls, there are now
len − str function calls.  And the greater the difference between original 
string length and desired string length, the more likely a stack overflow.


HTH

PointedEars
-- 
    realism:    HTML 4.01 Strict
    evangelism: XHTML 1.0 Strict
    madness:    XHTML 1.1 as application/xhtml+xml
                                                    -- Bjoern Hoehrmann

[toc] | [prev] | [next] | [standalone]


#14663

From"Michael Haufe (TNO)" <tno@thenewobjective.com>
Date2012-06-25 20:19 -0700
Message-ID<ad593911-0b87-4e09-8349-e443390e7d88@googlegroups.com>
In reply to#14641
On Saturday, June 23, 2012 8:51:50 PM UTC-5, Thomas &#39;PointedEars&#39; Lahn wrote:
> Michael Haufe (TNO) wrote:
> 
> > Thomas &#39;PointedEars&#39; Lahn wrote:
> >> Having reviewed these two solutions (see below), I still prefer mine...
> > 
> > I would have preferred my second solution mentioned to be evaluated, which
> > was added to the jsperf website:
> 
> The disadvantage of Google Groups postings to the interested poster is that 
> I do not see them (which is an advantage to me in most other cases), except 
> when they are followups to my postings and the poster was not killfiled.  
> Since I am not alone in this, I strongly suggest you switch to a more 
> responsible Usenet access provider.
>  
> > function padLeft(str, ch, len){
> >     return str.length >= len ? str : padLeft(ch + str, ch, len);
> > }
> 
> I do not think this recursive solution is very efficient or compatible 
> either.  Instead of a fixed number of 2 function calls, there are now
> len - str function calls.  And the greater the difference between original 
> string length and desired string length, the more likely a stack overflow.
> 

Any argument with regards to compatibility concerns is not
very useful without explicit constraints. Even if they were
presented, they would be debateable anyway. I am of the
belief that such concerns are best left to an ES current ->
ES legacy compiler. Many defensive programming techniques
are also better left to this methodology as well. 

Your efficiency argument is valid in part. I could make an
argument in reference to brevity and network traffic, but 
it is not significant enough in my opinion to pursue; plus
I doubt you were refering to anything beyond time/space 
with the efficiency criticism.

IRT speed, JSPerf demonstrates that this is not an issue in
relationto the other approaches presented there.

IRT to memory, it is indeed plausible (however unlikely)
that a string which needs to be padded to a significant
length could consume more memory than is desirable but if
memory was a concern, I find it unlikely that the developer
would be padding a massive string in the first place. Even so,
I think it is also worth noting that strings are constructed
lazily in more than one current browser. It is also well known
that tracing JITs do quite well with such code as it is type
stable and easily converted to loop (which is probably what
is demonstrated on the test page)

Stack overflow probability? I believe the worst offender would
be Safari 3.2 which has a 500 level limit. So what is the
probability that a developer is performing a left pad of 500
characters for a legacy client? I wouldn't pretend to know
without more information.

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | comp.lang.javascript


csiph-web