views:

108

answers:

2

This code trims whitespace, (fyi: it's credited to be very fast)

function wSpaceTrim(s){
    var start = -1,
    end = s.length;
    while (s.charCodeAt(--end) < 33 );  //here
    while (s.charCodeAt(++start) < 33 );  //here also 
    return s.slice( start, end + 1 );
}

The while loops don't have brackets, how would i correctly add brackets to this code?

while(iMean){
  // like this;
}

Thank you so much!

+7  A: 

The loop bodies are empty (the actual thing that happens is the increment/decrement operation within the loop condition), so simply add {}:

while (s.charCodeAt(--end) < 33 ){}
while (s.charCodeAt(++start) < 33 ){}

A longer, and probably easier to read version of the same while loop would be:

end = end - 1;
while (s.charCodeAt(end) < 33 )
{
    end = end - 1;
}
start = start + 1;
while (s.charCodeAt(start) < 33 )
{
    start = start + 1;
}
0xA3
if they're empty are they doing anything?
Mohammad
Oh, they're changing the variables `end` and `start` aren't they?
Mohammad
Maybe add a comment like this: { /* explaining what you're doing won't harm */ }
Oblio
Yep, the side effects are inside the expression and not the body
Sean Kinsey
ah, google closure gave me a warning and I needed to check this out : ) Thanks everyone!
Mohammad
@Mohammad if you add a test at the end so that you only call "slice" if there are actually spaces to be trimmed, it will really speed up the case of no trimming necessary.
Pointy
@Pointy, but doest `test()` search through all the string for the pattern, wouldn't that actually be slower than just committing to a slice that returns everything?
Mohammad
No no I don't mean "test()", I mean "a test"; in other words, a comparison to see if the call to "slice()" will actually do anything.
Pointy
+1  A: 

The code doesn't need brackets, but it does need an option to use a native trim method.

Opera, Firefox and Chrome all have a native string prototype trim function- the other browsers could add it as well. For this particular method, I think I would monkey a bit with the String.prototype, so as to use the built in method where possible.

if(!String.prototype.trim){
    String.prototype.trim= function(){
        var start= -1,
        end= this.length;
        while(this.charCodeAt(--end)< 33);
        while(this.charCodeAt(++start)< 33);
        return this.slice(start, end + 1);
    }
}

This may indeed be fast, but I prefer simple-

if(!(''.trim)){
    String.prototype.trim= function(){
        return this.replace(/^\s+|\s+$/g,'');
    }
}
kennebec
I'd expect this to be pretty fast actually, since the replace function is implemented in C, or C++ (whatever the browser is written in). It's a bit slower inherently because it uses regexps, but being compiled into native code probably more than makes up for that.
intuited