• ray10k (unregistered)

    Surprising that there's no comment to the effect of "It works, I don't know why, don't mess with this" at the top.

  • ray10k (unregistered)

    Surprising that there's no comment to the effect of "It works, I don't know why, don't mess with this" at the top.

  • LCrawford (unregistered)

    I'll bet someone spent time trying to figure out why StringToInteger ("-2") gave 100 as a result, after all the comment said 'only for small numbers'.

  • Patrick Tingen (unregistered) in reply to LCrawford

    If I read it correctly, it will return -1 for all values that are not in the range 0-100

  • some ron (unregistered)

    This implementation is obviously stupid. You can easily optimize it by putting all strings and numbers in a hashmap (or "object" if you speak only JavaScript) at program start even better or lazily on first use and simply lookup the number! That improves the runtime to amortized O(1)! See? There are better implementations! But there is probably not one better as mine.

    PS: I challenge you to find an implementation in spirit of the original, that is better than the original, but of course without resorting to the boring one.

  • Little Bobby Tables (unregistered)

    When you ask a child of four what the biggest number is, it will often reply with great enthusiam: "A hundred!"

    So there's your WTF, right there, asking a four-year-old to write business code.

  • a person (unregistered) in reply to some ron

    I'll try:

    function StringToInteger (str) {
        var isNegative = /^-/.test(str);
        var max=pow(10,str.length)/* try only numbers that are between 0 and the maximum number the string can be with its current length */;
        for (var i = 0; abs(i) < max; i += (isNegative ? -1 : 1) /* handle negative numbers */) {
            if (i /* no need to explicitly convert type, js can do that implicitly */ == str) return i;
        }
    
        return null /* sensible return value that isn't a valid value */;
    }
    
  • (nodebb)

    How do you know that this function isn't called from, say: function bigString2Integer(str) { var candidate=str.substr(-2); var result=0; while (candidate.length > 0) { result = result*100 + StringToInteger(candidate); var nxt = str.substr(0,candidate.length-2); candidate=nxt.substr(-2); } return result; }

    Addendum 2019-08-14 08:40: WTF? I cannot format my comment?

  • Little Bobby Tables (unregistered) in reply to some ron

    Okay, try this:

    //use for a little bit bigger numbers
    function StringToBiggerInteger (str) {
        var int = -1;
        var j = 0;
        for (var k = 0; k <= 6; k++) {
            for (var i = 0; i <= 9; i++) {
                if (i+"" == substring (str, k, 1) {
                    int = int + i;
                    break;
                }
             }
             int = int * 10;
        }
        return int;
    }
    

    I haven't tested the above, so it's iffy as to whether it works.

  • John (unregistered)

    "spirit of the original"

    //use only for small unsigned numbers function StringToInteger (s) { for (var i=0; i<=100; i++) { if (i+"" == s) { return i; } } return -1; }

  • Sandman (unregistered) in reply to LCrawford

    Maybe it's some strange way of testing if a numeric string is between 0 and 100? BTW "-2" yields -1, so not quite sure what you mean.

  • Expert Skillz (unregistered)

    It's far more efficient to compare integer types than string types, so writing the loop with integer comparison would improve the O(n) by a factor of 1.

    I also used a const for the max number so that will be easy to change when the requirements change.

    function StringToInteger (str) {
        const INVALID_NUMBER = -1;
        const MAX_NUMBER = 100;
        for (var i=0; i<=MAX_NUMBER; i++) {
            if (i == parseInt(str)) {
                return i;
            }
        }
        return INVALID_NUMBER;
    }
    

    An experienced coded could combine this with Bobby's suggestion to make the ultimate function

    function StringToBiggerInteger (str) {
        const INVALID_NUMBER = -1;
        const MAX_DIGIT = 9;
        var int = 0;
        for (var k = 0; k < str.length; k++) {
            for (var i = 0; i <= MAX_DIGIT; i++) {
                if (i == parseInt(substring(str, k, 1))) {
                    int = int + i;
                    break;
                }
             }
             int = int * 10;
        }
        return int;
    }
    
  • Reginald P. Smithington (unregistered)

    I'm suddenly reminded of a former co-worker. I asked him if he ever read The Daily WTF. He said he used to but they kept making fun of things that he thought were good ideas.

  • Calli Arcale (unregistered) in reply to Little Bobby Tables

    When you ask a child of four what the biggest number is, it will often reply with great enthusiam: "A hundred!"

    I have a distinct memory from when I was about that age, proudly demonstrating my newly earned skill in counting. 1, 2, 3, 4, 5, 6, etc for a while, and then jumping to hundred, thousand, million, billion, trillion, jillion, zillion, gajillon, and then on into whatever else I could come up with that ended with "illion" before ending with "googol", because someone had told me that was a very big number, and I was extremely proud to show off that I knew about it. ;-)

    Yeah, never ask four-year-old to design your business logic, for a whole lot of reasons. :-P

  • TheQuietOne (unregistered) in reply to Little Bobby Tables

    You say this as if the folks writing so-called "Enterprise Code" don't program at a mental age of a 4 year old. Or at least, that's what management tells the developers to do...

  • Ross Presser (unregistered)

    This WTF neatly combines two of the most popular approaches to quantum gravity: String Theory and Loop Quantum Gravity.

  • (nodebb)

    This WTF neatly combines two of the most popular approaches to quantum gravity: String Theory and Loop Quantum Gravity.

  • Bubba (unregistered)

    Rumor has it that remyporter.com has more than one employee

  • King (unregistered)

    StringToInteger("01") return -1.

  • Daniel (unregistered)

    At least they break out of the loop if it matches

  • SomeGuy (unregistered) in reply to a person

    Needs more JQuery

  • Reginald P. Smithington (unregistered) in reply to SomeGuy

    And a microservice string converter.

  • Worf (unregistered) in reply to some ron

    Well, instead of trying the numbers in order, why not try the numbers randomly from 0 to 100?

    Everyone knows it takes longer if you have numbers just slightly smaller than 100, so if you know you're going to have numbers from 80 to 100, randomly trying numbers might be faster since you're not constantly checking 1, 2, 3, ... 79 all the time. And you might hit it the first time making it extremely fast!

  • NoLand (unregistered)

    Fixed it:

    function StringToBinaryAssertedInteger(str) { function nextInt(i) { var x = i.length - 1; while (i.charAt(x) === '1') { i = i.substring(0, x) + '0' + i.substring(x + 1); if (--x < 0) break; } if (x >= 0) { i = i.substring(0, x) + '1' + i.substring(x + 1); } else { i = '1' + i; } return i; } for (var i = '0'; i !== '1100100'; i = nextInt(i)) { if (i === parseInt(i).toString(2)) return parseInt(i, 2); } return 'fileNotFound'; }

  • NoLand (unregistered)

    Fixing the fix (formatting)?

    function StringToBinaryAssertedInteger(str) { function nextInt(i) { var x = i.length - 1; while (i.charAt(x) === '1') { i = i.substring(0, x) + '0' + i.substring(x + 1); if (--x < 0) break; } if (x >= 0) { i = i.substring(0, x) + '1' + i.substring(x + 1); } else { i = '1' + i; } return i; } for (var i = '0'; i !== '1100100'; i = nextInt(i)) { if (i === parseInt(i).toString(2)) return parseInt(i, 2); } return 'fileNotFound'; }

  • Officer Johnny Holzkopf (unregistered) in reply to TheQuietOne

    Why should I pay those so-called programmers, developers, or software engineers? Anyone can make business apps! It's super easy because the PC knows what it is supposed to do. My 4 year old son could write a whole business suite in a weekend! He's good with computers, you know? He has an . . . aaayyyy-Paaaaaaaaad!

  • tlhonmey (unregistered)

    Looks like a modern speedup loop to me. Compilers and interpreters these days will just optimize away empty loops, but if the loop is actually doing something they can't touch it no matter how inefficient it may be.

  • MD (unregistered) in reply to Reginald P. Smithington

    Ok, this is going to be one of my questions at any job interview from now on (from both sides of the table). A response like this will be a hard no. Again, from either side of the table.

  • Dave (unregistered) in reply to Calli Arcale

    OTOH four year olds make great testers. Years ago I wrote some incredibly basic instructions for something utterly trivial like how to log in to a website. Co-worker had brought her 4 y/o into the office for a couple of hours for some reason or other, so we got him to test the instructions.

    A while later the boss complained he couldn't follow the instructions. Asked if I'd even got anyone else to test them. I said yes, a four year old had no trouble...

  • Little Bobby Tables (unregistered)

    Hey guys, we can do better than that:

    function StringToIntegerInWhateverNumberBase (str, numberBase) {
        const INVALID_NUMBER = -1;
        var int = 0;
        for (var k = 0; k < str.length; k++) {
            for (var i = 0; i < numberBase; i++) {
                if (i == parseInt(substring(str, k, 1))) {
                    int = int + i;
                    break;
                }
             }
             int = int * numberBase;
        }
        return int;
    }
    
  • (nodebb)

    My JS is really rusty, so let's see if I can figure this out based on my experience with C/C++/C#. Let's see String2Integer with lots of looping. Here you go:

    function String2Integer(str)
    {
       var IsNegative = false;
       var Position = 0;
       var Result = 0;
    
       // Check for negative
       if (str.charAt(Position) == '-')
       {
          IsNegative = true;
          ++Position;
       }
       else if(str.charAt(Position) == '+')
       {
          // Just skip a leading +.
          ++Position;
       }
    
       while (Position < str.length())
       {
          if(str.charAt(Position) >= '0' && str.charAt(Position)<='9')
          {
             Result *= 10;
             Result += str.charAt(Position) - '0';
             ++Position;
          }
          else
             // No decimal points or hexadecimal characters, so invalid input.  Abort!
             return null;
       }  // while (Position < str.length())
       if (IsNegative)
          return -Result;
       else
          return Result;
    }
    
  • Argle (unregistered) in reply to Reginald P. Smithington

    This is why we well never run out of WFTs.

  • (nodebb)

    The loop is too long. It should be either ...for (var i=0; i<100; i++)... or ...for (var i=1; i<=100; i++)...

    My brain works zero-based, so I would always use the first, but feel free to use the second form

    I have seen too many bugs creep in like that.

  • (nodebb)

    Also, why not define an array (preferrably hardcoded, of course) containing the values you wish to check? That way, you can properly iterate through it with Array.prototype.forEach

  • Worf (unregistered) in reply to Dave

    The problem is, 4 year olds generally follow instructions. Thus when you give them instructions, as long as they're accurate, they'll be successful. It seems as we grow older our ability to follow instructions wanes and so steps are skipped and shortcuts taken.

  • (nodebb) in reply to King
    StringToInteger("01") return -1.

    Yeah, right. That is the biggest problem with this function.

  • (nodebb) in reply to King

    I would assume (I know, TMOAFU), this function was not intended for converting octal numbers.

  • anonymous (unregistered)

    I like this rather clever way to convert an integer to a string. Too bad the language (which I'm assuming is JavaScript) already does that automatically when you compare an integer and a string.

Leave a comment on “A Loop in the String”

Log In or post as a guest

Replying to comment #:

« Return to Article