Re: Padding fixed-length strings



Richard Maher wrote on 15 apr 2007 in comp.lang.javascript:

I wrote:
function fixedLength(s,n){
n = (n<0) ?0 :n
s = s.substr(0,n);
var a = [];
a.length = n - s.length + 1; // never negative <--------------
return s + a.join(' ');
};



I like it. I'll use the Array length/join(' ') at initialize time as a
sort of space$() function to preallocate a maximum space-filled
string, but then stick to substringing out of that the number of space
bytes I need for padding.

Did some testing:

alert(new Array(17).length); // 17
alert(new Array(17).join('?').length); // 16

alert(new Array('17').length); // 1 <-----------------
alert(new Array('17').join('?').length); // 2 <-------------

alert(new Array(0).length); // 0
alert(new Array(0).join('?').length); // 0
// alert(new Array(-3).length); // error


function newArray(n){
var a = [];
a.length = n;
return a;
}

alert(newArray(17).length); // 17
alert(newArray(17).join('?').length); // 16

alert(newArray('17').length); // 17 <------------------
alert(newArray('17').join('?').length); // 16 <-------------

alert(newArray(0).length); // 0
alert(newArray(0).join('?').length); // 0
// alert(newArray(-3).length); // error

;-)

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



Relevant Pages

  • Re: Variable variables stored in an array and called == problem.
    ... I have an array: ... The Netherlands. ... (Please change the x'es to dots in my emailaddress) ...
    (comp.lang.javascript)
  • Re: Multiple radios with same names & predefined key value
    ... where just> is html. ... optionssuggests an array, but an input name cannot be an array. ... (Please change the x'es to dots in my emailaddress) ...
    (comp.lang.javascript)
  • Re: scan dpi for photos
    ... A digital photograph is essentially an array, ... Each element in the array is called a pixel, ... inkjet, DM, or laser printers all the dots are the same size. ... does for the complex "dithering" you speak. ...
    (rec.photo.digital)
  • Re: Collections of structured-data objects: what approach?
    ... connecting the dots might help others stumbling along this way, and you never know it might turn out that your "consistency" comment was referring to something else I didn't see. ... the reason is probably that Array and Hash are so powerful on the one hand and that requirements are so different on the other hand. ...
    (comp.lang.ruby)
  • Re: Imaginary Polynomial Time Algorithm for Subset sum Problem
    ... While on any realistic computer/model, copying an array, would take time proportional to its size. ... copying an array does not take up time which is proportional to the size of the array on a parallel computer. ... This is not the case of the OP's stamping process which copy as many dots as wanted in time 1 without explicitely creating all these processors. ...
    (comp.theory)

Loading