Article 4N8RC CodeSOD: A Loop in the String

CodeSOD: A Loop in the String

by
Remy Porter
from The Daily WTF on (#4N8RC)

Robert was browsing through a little JavaScript used at his organization, and found this gem of type conversion.

//use only for small numbersfunction StringToInteger (str) { var int = -1; for (var i=0; i<=100; i++) { if (i+"" == str) { int = i; break; } } return int;}

So, this takes our input str, which is presumably a string, and it starts counting from 0 to 100. i+"" coerces the integer value to a string, which we compare against our string. If it's a match, we'll store that value and break out of the loop.

Obviously, this has a glaring flaw: the 100 is hardcoded. So what we really need to do is add a search_low and search_high parameter, so we can write the for loop as i = search_low; i <= search_high; i++ instead. Because that's the only glaring flaw in this code. I can't think of any possible better way of converting strings to integers. Not a one.

buildmaster-icon.png [Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today! TheDailyWtf?d=yIl2AUoC8zAZS5XCo87aPk
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments