John
John

Reputation: 53

Weird JavaScript Code

for (var i=a.length-1;i>0;i--) {
    if (i!=a.indexOf(a.charAt(i))) {
        a=a.substring(0,i)+a.substring(i+1);
    }
}

I found this in a web app I'm auditing, it just baffles me why it's there. I can't seem to see a case where i!=a.indexOf(a.charAt(i)) would be false.

The value the pass to it is:

a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

There is no comment either //sigh

Upvotes: 2

Views: 624

Answers (1)

Domenic
Domenic

Reputation: 112807

This would be true for repeated characters, since indexOf finds the first index of a string, and you're searching from the end. Example:

var a = "xyzxyz";

On first iteration, i === 4, a.charAt(4) === "x", and a.indexOf("x") === 0. So 4 !== 0.

It then sets a = a.substring(0, 4) + a.substring(5). Recalling at substring is inclusive in the first index but exclusive in the last index, that means in this case a = "xyz" + "yz", so we have removed the duplicate "x" from the string.

Since the loop traverses backward, this will continue to work even for characters repeated more than once; you can see that the portion a.substring(i + 1) will always have been covered by the algorithm already, i.e. not contain any duplicates.


As always when encountering this type of thing, applying the extract method refactoring would be a great way to make the code clearer. (Even better than commenting it!) So if you just pulled this out into a method, the code could become a = removeDuplicateChars(a), and everyone is much happier.

Upvotes: 6

Related Questions