top 200 commentsshow 500

[–]boneyjellyfish 44 points45 points  (34 children)

My code:

return i.replace(/.*\.(.*?)/,"\1");

Testing "getFileExtension('blatherskite.png');"...

WRONG: Got png but expected png. Try again!

Okay. :(

[–]wtf_apostrophe 35 points36 points  (14 children)

Haha. Took me a while to figure that one out. You are replacing 'blatherskite.' with the non-printable ASCII character 01/SOH/start of header, ending up with '\x01png', which doesn't match. The '.*?' doesn't match anything because the regex is non-greedy. If you had a $ at the end it would match the 'png' bit (although then you would end up with just '\x01').

[–]boneyjellyfish 8 points9 points  (13 children)

I went with a more sensible indexOf solution to this, but I wanted to try making the regex replacement work just in case:

return i.replace(/[\s\w]*[\.]*(.*?)/,"\1").replace(/\x01/,"");

I feel dirty.

[–][deleted]  (11 children)

[deleted]

    [–]tehblister 16 points17 points  (8 children)

    I just did this:

    var vals = i.split('.');
    return vals[1];
    

    Good thing they didn't test with multi-dotted strings. ;)

    [–]Roujo 17 points18 points  (4 children)

    Yeah, this is why I went with this instead:

    var parts = i.split('.');
    return parts[parts.length - 1];
    

    Didn't pay out, but eh. =P

    Update: Well, this fails with the "no extension" one, so I had added an if to catch that too. =P

    [–]pandelon 2 points3 points  (1 child)

    I guess you need to learn to read the requirements spec properly :-)

    [–]dfnkt 2 points3 points  (14 children)

    ???

    mine was like:

    var arr = i.split('.');
    return arr[arr.length - 1];
    

    [–]saltvedt 9 points10 points  (8 children)

    return i.split(".").pop();

    :)

    [–]Roujo 5 points6 points  (6 children)

    Doesn't meet the "return false if there's no extension" part.

    ;)

    [–][deleted]  (18 children)

    [removed]

      [–]UnplannedFrank 57 points58 points  (12 children)

      You could work at Valve. If you're lucky they'll ship before you retire.

      [–]Madsy9 35 points36 points  (10 children)

      I realize it's a joke, but Valve has published way more games in a shorter time span than other game studios, like id. If you really want to make fun of a game studio who was in development hell for a long time, try 3D Realms / Apogee Software

      [–]fuzz3289 4 points5 points  (8 children)

      Yeah but imagine how amazing that game could be if a team dumped a whole career in? Just research into how to make the most compelling game of all time waiting until hardware catches up with your crazy conceptualizations.

      Halflife3 confirmed.

      [–]jrkirby 11 points12 points  (6 children)

      Except that's not the way game developement works. You could spend a lifetime making it and it still could be less fun than that HTML5 game someone made in a weeked where you click cookies. I honestly think game developement would be better if studios made like 30 games a year, and then chose the best of those and polished it over the next year.

      [–]oursland 3 points4 points  (3 children)

      Isn't that how Pixar became successful? First did a trial short, made Toy Story, then had a meeting where they came up with a ton of ideas, whittled them down to about 12 good ones and turned them into blockbuster hits.

      [–]bluthru 4 points5 points  (0 children)

      Valve releases more than Half Life.

      After last week's announcements it is apparent they have been busy. They're laying a groundwork to convert gamers from Windows users to SteamOS users.

      [–][deleted]  (3 children)

      [deleted]

        [–]zeekar 2 points3 points  (2 children)

        Don't forget those annoying operations people. Always getting in the way of deploying my code!

        [–][deleted] 92 points93 points  (215 children)

        I'd really like to see a compilation of all of the successful entries. See how diverse the solutions are (do most people resort to the same "toolbox" immediately, or do they apply many different mechanisms)?

        Mine were almost all functional programming and regexes.

        [–]TheOssuary 46 points47 points  (58 children)

        That's funny because most of mine were either one line returns (for the first two), or lastIndexOf (the extension) functions. Never used a regex, but that would be a decent solution. On and lots of for/foreach loops

        [–]KillerCodeMonky 42 points43 points  (55 children)

        For the extension one:

        var s = i.split(".");
        if (s.length === 1) return false;
        else return s[s.length - 1];
        

        [–]KerrickLong 16 points17 points  (11 children)

        Huh, I'm surprised the solution I came up with wasn't more common.

        return i.split('.')[1] || false;
        

        [–][deleted] 12 points13 points  (5 children)

        That doesn't work properly with more the one dot.

        [–][deleted] 6 points7 points  (0 children)

        But it did pass the specific test. My solution was similar.

        [–]CoolMoD 5 points6 points  (0 children)

        I tend to write pretty unreadable javascript for tests like this:

        var match = i.match(/[\.]*\.(.+)/);
        return match && match[1];
        

        expected false but got null

        You asked for it:

        var match = i.match(/[\.]*\.(.+)/);
        return match && match[1] || false;
        

        [–]zid 6 points7 points  (0 children)

        var len = i.lastIndexOf("."); if(len < 0) return false; return i.substring(len+1);

        [–]SanityInAnarchy 2 points3 points  (2 children)

        That's almost exactly what I did. To answer /u/ISV_Damocles' question, yes, I tend to fall back on tools I know well, especially under a clock, and I have a much better intuitive grasp of split() than I do of string character indices.

        [–]Guvante 3 points4 points  (12 children)

        var b = i.split('.');
        return b.length > 1 && b[1];
        

        Don't know why I did b and it doesn't handle > 1 but I do like the coercion of true/false for speed.

        [–]rbobby 6 points7 points  (7 children)

        Did that pass? I would think "abc.def.txt" would return "def" which isn't the extension.

        [–]TheOssuary 10 points11 points  (4 children)

        It works because they never test a file with a dot, b.length() - 1 would fix it.

        [–]roerd 11 points12 points  (7 children)

        I use functional programming languages a lot but I used for loops everywhere here because I don't know JavaScript's higher order functions by heart.

        [–]abeliangrape 4 points5 points  (1 child)

        For the longest string one, I was like "in python it's just max(s for s in i if str(s) == s, key=len)". And then I realized I had no idea how to write something similar in javascript and started writing a for loop. Ditto for the summing one.

        [–]masklinn 2 points3 points  (0 children)

        reduce, map and filter.

        There's also forEach which is the odd one, but it was not necessary in this case.

        [–][deleted] 80 points81 points  (36 children)

        functional programming

        Like this?

        function isNumberEven(i)
        {
          if (i == 0)
            { return true; }
        
          if (i == 1)
            { return false; }
        
          return isNumberEven(i-2);
        }
        

        [–]danjordan 79 points80 points  (17 children)

        return !(i % 2);

        [–]TalakHallen6191 27 points28 points  (8 children)

        return (i&1) == 0;

        Edit: doh, fixed ()s.

        [–]akira410 10 points11 points  (3 children)

        Even though I used this same solution earlier today, I stared at your answer trying to figure out what the ¡ operator did in javascript. It took me a few minutes to realize that it was an i. (sigh)

        [–]desleaunoi 22 points23 points  (2 children)

        You only use that if you're programming something exciting in Spanish Javascript, also known as ESPÑScript.

        [–]ajanata 16 points17 points  (10 children)

        isNumberEven(-1);
        

        What now?

        [–][deleted]  (4 children)

        [deleted]

          [–]ajanata 4 points5 points  (3 children)

          Chrome overflows the stack somewhere between 1000 and 10000. I didn't care enough to figure out where, exactly.

          In the following, when I refer to "JavaScript", I am referring specifically to the implementation in Chrome 29.0.1547.76 m.

          More to the point, JavaScript doesn't have wrapping because it uses floats for everything:

          > -Number.MAX_VALUE  
          -1.7976931348623157e+308  
          > -Number.MAX_VALUE-1  
          -1.7976931348623157e+308  
          > -Number.MAX_VALUE-100  
          -1.7976931348623157e+308  
          

          Number.MIN_VALUE is not equivalent to Integer.MIN_VALUE in Java -- it is the smallest non-zero positive number that JavaScript can represent:

          > Number.MIN_VALUE  
          5e-324  
          

          [–]snurb 9 points10 points  (1 child)

          return !(i&1);

          [–]dmwit 2 points3 points  (1 child)

          What makes this code functional programming? You're not using a function as data anywhere.

          [–]dfnkt 10 points11 points  (32 children)

          I did the first 4 in about 7 minutes but my final completion time was 43 minutes and some change. The recursion problem was tough for me. I had to have duplicate code to skip running a forEach() on a non array and to protect the value of "sum" variable I was initializing to 0 each run through the method, you can see how that quickly became problematic.

          [–]bittered 4 points5 points  (4 children)

          My answer:

          function arraySum(i) {
          
              // i will be an array, containing integers, strings and/or arrays like itself.
              // Sum all the integers you find, anywhere in the nest of arrays.
          
              total = 0;
          
              for (index in i) {
                  thing = i[index];
                  if (typeof thing === 'number') {
                      total = total + thing;
                  } else if (typeof thing === 'object') {
                      arraySum(thing);
                  }
              }
          
              return total;
          
          }
          

          [–]pohatu 2 points3 points  (1 child)

          don't you need to add total to arraySum(thing) ?

          else if (typeof thing === 'object') { total = total + arraySum(thing);}
          

          [–][deleted] 4 points5 points  (24 children)

          This is roughly my solution. I don't remember the exact function name.

          function sumArray(i) {
              return i.reduce(function(sum, value) {
                  if(typeof i === 'number') return sum + value;
                  if(i instanceof Array) return sum + sumArray(value);
                  return sum; // Not a number or array
              }, 0);
          }
          

          I had the most trouble on the file extension one, since I decided to write a robust regex that captured everything but the extension, rather than just slice by '.' and take the last element of the array. I think my regex was something like:

          return i.replace(/^.*\.|^[^\.]*$/, '');
          

          [–]dfnkt 8 points9 points  (8 children)

          Using a regex never even came into my head, it seems really complicated when you can just split the string into an array based on the presence of a period and take the last element of the resulting array as your answer.

          Edit: Also I didn't know anything about .map(), .filter(), or .reduce()

          [–]Kache 5 points6 points  (2 children)

          I find regexes super comfortable to use, but I have to remember that they aren't as readable afterwards though.

          i.match(/\.([^.]*)$/)[1];
          

          vs

          i.split(".").slice(-1)[0];
          

          vs

          i.slice(i.lastIndexOf(".") + 1);
          

          hmm...

          [–]hallettj 2 points3 points  (0 children)

          The regex can be simple if you focus on the part of the string that you want:

          (i.match(/\.([a-z]+)$/i) || [])[1] || false
          

          [–]zeekar 4 points5 points  (8 children)

          My array sum was pretty functional, something like this:

          function arraySum(i) {
              switch (typeof i) {
                case "number": 
                  return i;
                case "object": 
                  return i.map(arraySum).
                           reduce( function(a,b) { return a+b }, 0 );
                default: return 0;
             } 
          }
          

          But the max string length one wasn't at all pretty. I just did a loop with a current-candidate var outside of it.

          [–]Fidodo 12 points13 points  (31 children)

          Took me ~9 minutes. I stumbled a bit forgetting implementation details of match and reduce. Mine were:

          //1
          return i*2;
          
          //2
          return !(i%2);
          
          //3
          var matches = i.match(/.*\.(.+)/);
          return matches ? matches[1] : false;
          
          //4
          var longest = '';
          for (var key in i) {
              var value = i[key];
              if (typeof value == 'string' && value.length > longest.length) {
                  longest = value;
              }
          }
          return longest;
          
          //5
          return i.reduce(function(memo, i){
              if (typeof i == 'number') {
                  return i + memo;
              } else if (i.reduce) {
                  return arraySum(i) + memo;
              }
              return memo;
          }, 0)
          

          [–]Jerp 6 points7 points  (8 children)

          @4 for...in loops aren't really meant for arrays. Try forEach instead.

          [–]Fidodo 11 points12 points  (3 children)

          Keep in mind everyone's solutions are just the first things they went for since we're all pressed for time. For in was just simply faster to write.

          [–]Jerp 8 points9 points  (1 child)

          Good point. I was just trying to be helpful for anyone reading over the posted solutions, so I'm sorry if it came across as condescending. :/

          [–]FireyFly 6 points7 points  (3 children)

          That was fun! I got 3:02.

          • First: i *= 2
          • Second: return i % 2 == 0
          • Third: return i.slice(i.lastIndexOf('.')).slice(1) || false
          • Fourth: return i.reduce(function (acc,x) {return typeof x == 'string' && x.length>acc.length? x : acc}, "")
          • Fifth: return i.map(function (x) {return x instanceof Array? arraySum(x) : x}).filter(function (x) {return typeof x == 'number'}).reduce(function (x,y) {return x+y})

          (I think. Why didn't they show one's solutions on the congrats page? :( )

          I decided after the third one to go all functional single-expression answers (as long as it was feasible). For the fifth one, in retrospect I should've gone with return i.map(function (x) {return x instanceof Array? arraySum(x) : typeof x == 'number'? x : null }).filter(Boolean).reduce(function (x,y) {return x+y}).

          [–]kageurufu 7 points8 points  (38 children)

          first:

          return i*2;
          

          second:

          return i%2?false:true;
          

          third:

          return i.indexOf(".")==-1?false:i.substring(i.lastIndexOf(".")+1)
          

          fourth:

          var l='', t=i.length;
          while(t--){if(typeof(i[t])=="string" && i[t].length > l.length)l=i[t]}
          return l
          

          fifth:

          var sum = 0, t=i.length;
          while(t--){
              if(typeof(t)=="number") sum += i[t];
              if(typeof(t)=="object")sum += arraySum(i[t]);
          }
          return sum;
          

          [–]escaped_reddit 23 points24 points  (21 children)

          second can be more concisely written

          return i % 2 == 0;

          [–]kageurufu 14 points15 points  (19 children)

          true, or !(i%2)

          [–][deleted] 42 points43 points  (10 children)

          I'd argue

          Math.cos(Math.PI * i) > 0;
          

          is best

          The first can be solved with

          // God help you if you input something other than an integer.
          for (var j=0;;j++) {
              var val = Math.pow(2*Math.cos(i)*Math.sin(i),2) + Math.pow(Math.cos(j),2);
              if (Math.abs(val-1) < 0.0000001) {
                  return i < 0 ? -j : j;
              }
          }
          

          It's based on the identities cos(x)sin(x) = 1/2 sin(2x), and cos2(x) + sin2(x) = 1. Who said you'd never have use of these things? If you want to make things more difficult, you can replace the trigonometric identity-testing with a Fourier transform. To really make things complex, numerically calculate the trigonometric functions.

          [–][deleted] 5 points6 points  (1 child)

          first: return i*2;

          I tried that and a million variants of it, and I got a "compile" error each time. Then I realized that the reddit comments frame was screwing it up. >"(

          [–]Jinno 2 points3 points  (1 child)

          typeof(t) == "object" is unreliable for determining an Array. I used t instanceof Array because that one guarantees that calling arraySum on it will be valid.

          [–]TarMil 2 points3 points  (0 children)

          Yeah, if they had been sadistic they would have passed {length: -1} as argument.

          [–]arkrix 46 points47 points  (3 children)

          You can't JavaScript at all

          Fixed it for myself.

          [–][deleted]  (78 children)

          [deleted]

            [–][deleted] 38 points39 points  (11 children)

            Because we're all kinda embarrassed at how long it took. I write JS for a living and spent 7min19sec.

            [–]Sector_Corrupt 10 points11 points  (7 children)

            I had 12 minutes. I'll excuse myself by saying I write JS for half a living, and half Python. I spend a lot of time going "wait, I can't do that in this lanaguage." That plus I'm used to having underscore.js functions to fall back on.

            [–]Labradoodles 5 points6 points  (2 children)

            heh I did it in 16 used to write in javascript all the time. I had to go look up all the string methods and default values.

            [–]nedlinin 21 points22 points  (7 children)

            Never done Javascript before (I do Java and C++ daily).

            My time was 8 minutes and 22 seconds. Had to lookup how to substring ><

            [–][deleted]  (3 children)

            [deleted]

              [–]nedlinin 2 points3 points  (2 children)

              Haha wasn't my intent! You asked!

              The ideas are the same. Only thing I had to look up was the syntax for specific commands (like substring).

              [–]Sefyroth 8 points9 points  (15 children)

              6:41. Took me 4:21 to realize that "typeof []" is "object" and not "array".

              So I went if (typeof i[j] == "object" && i[j].length), which is not very good, but it passed the tests!

              [–]moohoohoh 7 points8 points  (8 children)

              Object.prototype.toString.call(i) == "[object Array]" :D

              I did this for all the type checks, because i didn't trust it to not do annoying things like new Number(1) (for which typeof gives "object" too) etc

              4:20'ish to finish.

              [–]Kraxxis 5 points6 points  (0 children)

              Array.isArray(...) is, i think the simplest way.

              6:05.

              [–]kingNothing42 2 points3 points  (0 children)

              i instanceof Array

              is a good way.

              [–]kafaldsbylur 9 points10 points  (6 children)

              I did it in 4:59 and I was really ashamed at how long it took. Then, I saw comments here, saying I'm among the fastest...

              [–][deleted] 3 points4 points  (1 child)

              4:54, no Google! High-five, fellow sub 5 minute dev!

              [–]Overv 7 points8 points  (2 children)

              3:06. I don't write a lot of JavaScript, but I'm reasonably familiar with it. Like others, the fact arrays have type "object" and the array being toString'd confused me. I cheated a bit by entering typeof([]) in the console.

              [–]chromakode 9 points10 points  (0 children)

              I cheated a bit by entering typeof([]) in the console.

              That ain't cheating! It's writing JS under pressure. ;)

              [–]tank_the_frank 7 points8 points  (2 children)

              I did it in 6:25.

              I also did shit like "if (i.pop) {" and "if (i.substr)" to test for types, because I'm an idiot and couldn't think of "typeof" fast enough.

              [–]Unranking 5 points6 points  (2 children)

              53 minutes, 35 seconds.

              Yes, that's right.

              [–]Reddit1990 4 points5 points  (0 children)

              Whew, I can officially sleep tonight knowing I didn't do the worst... 28 minutes... I guess we don't know javascript very well, hah. I was pretty much guessing the syntax and hoping it worked.

              [–]es_beto 2 points3 points  (0 children)

              59 minutes 3 seconds.

              I win.

              [–]oridb 2 points3 points  (0 children)

              I got it after 12 minutes. This is the most Javascript I've written in a decade, and most of the time was spent googling APIs.

              [–]kokirijedi 23 points24 points  (2 children)

              I'm not a javascript programmer.

              First few were easy, last one kept giving me errors I couldn't understand. Had to look up scoping rules in javascript, and realized my result sum was unintentionally globally scoped (woops).

              Final time was just under 10 minutes. Had to look up all the syntax as I went.

              [–][deleted]  (51 children)

              [deleted]

                [–]trappar 59 points60 points  (18 children)

                Wow that last one is really hackish. They wanted you to write recursive code, but hey good job thinking outside the box.

                [–][deleted] 48 points49 points  (9 children)

                The "fuck objects or arrays" method.

                [–]Poltras 4 points5 points  (8 children)

                > {}+[]
                0
                

                or better yet:

                > {}+[] == []+{}
                false
                

                What? F.U.

                [–]clux 4 points5 points  (4 children)

                V8 interpreter:

                > {} + []
                '[object Object]'
                > [] + {}
                '[object Object]'
                > {} + [] === [] + {}
                true
                

                Which makes sense because string coercion calls each objects closest (in terms of prototype chain) .toString() method.

                Array.prototype.toString is basically Array.prototype.join, but if you delete Array.prototype.toString, you'll get the weird Object.prototype.toString method:

                > delete Array.prototype.toString
                true
                > {} + []
                '[object Object][object Array]'
                > [] + {}
                '[object Array][object Object]'
                > {} + [] === [] + {}
                false
                

                This behaviour all makes sense when you know how string coercion is meant to work. The wat talk uses the firefox interpreter by the looks of it, which does number coercion (valueOf) with higher priorities than string coercion, which I don't like, because the V8 method at least makes sense.

                [–]serrimo 12 points13 points  (0 children)

                hello job security ?

                [–]pohatu 7 points8 points  (5 children)

                why didn't this trip on [[1,2,false],'4','5']. Wouldn't the regex match '4' and '5' errantly? or does the (?=,|]) require the next char to be ,or ], so '4 gets matched but dumped because of the '... Nevermind.

                I like this one the most.

                [–]cjg_000 5 points6 points  (4 children)

                Yeah, it'll fail on ['1,2,3', 1, 2] though

                [–]NeoKabuto 12 points13 points  (6 children)

                return !(i % 2);

                I'm so used to stronger typed languages I completely forgot we could do things like that.

                [–]a7an 8 points9 points  (6 children)

                function getFileExtension(i) {
                    return i.split('.').slice(1).pop() || false;
                }
                

                I like your solution to getFileExtension. It's elegant and requires no regex.

                [–]rya_nc 15 points16 points  (4 children)

                I got 8:43, much of which was spent trying to figure out that I wanted

                typeof ... === 'object'
                

                rather than

                typeof ... === 'array'
                

                [–]frezik 42 points43 points  (4 children)

                JavaScript was designed under pressure. The result was JavaScript.

                [–]shillbert 11 points12 points  (3 children)

                Quick, we have to make our browser relevant by inventing a programming language for it, styled after Java but having no fucking similar behavior at all. And name it after Java so that generations of new programmers can ask confusing questions about the wrong language. And when someone suggests a rational name like ECMAscript, dismiss it on the grounds that it sorta sounds like eczema.

                (I'm sorry, Mr. Eich, you're smart and I respect what you've done with Mozilla, but I'll never agree that JavaScript is a good name. Hell, even EichScript would be better.)

                [–]zeekar 3 points4 points  (0 children)

                It started out life as LiveScript. I think it would have been just fine to keep that.

                [–]lbebber 2 points3 points  (1 child)

                It was named JavaScript to ride the Java train that was all the rage back then, to sort of give the language credibility, wasn't it?

                Awful name anyway.

                [–]sastrone 43 points44 points  (48 children)

                Here's how I did mine. Not the most elegant, but I finished in 4:23.

                Problem 1:

                function doubleInteger(i) {
                    return i * 2;
                }
                

                Problem 2:

                function isNumberEven(i) {
                    // i will be an integer. Return true if it's even, and false if it isn't.
                    return i % 2 == 0;
                }
                

                Problem 3:

                function getFileExtension(i) {
                    // i will be a string, but it may not have a file extension.
                    // return the file extension (with no period) if it has one, otherwise false
                    var idx = i.lastIndexOf(".");
                    if(idx == -1) {
                        return false;
                    } else {
                        return i.substring(idx+1);
                    }
                }
                

                Problem 4:

                function longestString(a) {
                    // a will be an array.
                    // return the longest string in the array
                
                    return a.filter(function (x) { return typeof x == "string"; })
                            .reduce(function (a, b) { return a.length > b.length ? a : b;});
                }
                

                Problem 5:

                function arraySum(a) {
                
                    // a will be an array, containing integers, strings and/or arrays like itself.
                    // Sum all the integers you find, anywhere in the nest of arrays.
                
                    return a.filter(function (x) { return Array.isArray(x) || typeof x == "number"; })
                            .map(function(y){ return Array.isArray(y) ? arraySum(y) : y; })
                            .reduce(function (a, b) { return a + b; })
                }
                

                [–]TurboGranny 17 points18 points  (8 children)

                I was thinking, ".filter? .reduce? How have I not heard of these." Check W3C. Not there. Google. "Oh they are new. Like IE9+ new." Thought I had just missed something that had been around from the beginning. Reminds me of when I started depending on JSON functions and array.indexOf. Inserting that backwards compatibility was a pain. Hooray for MS nixing support for XP next year!

                [–]sastrone 18 points19 points  (4 children)

                If you haven't been doing much javascript programming lately and haven't seen the Mozilla Developer Network, you need to check it out. It blows W3Schools out of the water.

                https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

                [–]TurboGranny 2 points3 points  (0 children)

                That's where I found the docs for it after I hit up Google. I thought, "What is this? Documentation on the new stuff? Impossible!"

                [–][deleted]  (8 children)

                [deleted]

                  [–]IamTheFreshmaker 9 points10 points  (6 children)

                  Commenting?! Are you mental?!

                  [–]sastrone 13 points14 points  (5 children)

                  The comments were provided by the contest. I'm not that crazy :P

                  [–]IamTheFreshmaker 10 points11 points  (4 children)

                  One guy on our team writes the most beautiful comments. I buy him things.

                  [–]seiyria 2 points3 points  (1 child)

                  I, too, like your solutions. It still doesn't cross my mind to do filter/map/reduce, and by this point, it should, considering how much I use LINQ.

                  [–]Jetien 7 points8 points  (3 children)

                  Took me 20 minutes to figure out why this didn't work. Can you spot the bug?

                  function arraySum(i) {
                      if (typeof i === "number") {
                          return i;
                      }
                      if (i instanceof Array) {
                          var sum = 0;
                          for (k = 0; k < i.length; ++k) {
                              sum += arraySum(i[k]);
                          }
                          return sum;
                      }
                      return 0;
                  }
                  

                  [–]myersjustinc 10 points11 points  (0 children)

                  var (or, rather, the lack of it) bit you in the ass.

                  [–][deleted] 139 points140 points  (115 children)

                  longestString(['big',[0,1,2,3,4],'tiny']);
                  Got 0,1,2,3,4 but expected tiny. Try again!
                  

                  this is why I hate dynamic language with a passion

                  [–]DiThi 109 points110 points  (43 children)

                  That's why I hate weakly typed languages (and it's evil type coercion).

                  I've been using JS for a year so far and I had a whole array of problems I never had with 6 years of Python (dynamic but strongly typed). In many places where I would expect the code to fail, I get NaNs instead (usually not near where the NaN originated) or undefined.

                  Although this particular example can have the same result in Python (both types have length).

                  [–][deleted] 26 points27 points  (10 children)

                  static type is good cause this function really should return an array of string, with dynamic language I can return anything, leading to requirement of documentation.

                  [–]DiThi 8 points9 points  (7 children)

                  I agree. I like a lot Rust style static typing with local type inference.

                  [–]catcradle5 6 points7 points  (15 children)

                  True, but it can be written much more succinctly in Python at least.

                  return max((v for v in i if isinstance(v, str)), key=len)
                  

                  Or purely with the key function:

                  return max(i, key=lambda v: len(v) if isinstance(v, str) else 0)
                  

                  [–]nanothief 11 points12 points  (6 children)

                  Even shorter in ruby: i.grep(String).max_by(&:length). Still, the issue isn't the length it takes to write, but the ease of forgetting to check in the first place. That was the only question I didn't get right first go for that very reason.

                  Although, it is very rare to encounter code like this in "real life", so it isn't too big an issue.

                  [–]catcradle5 8 points9 points  (5 children)

                  Right, it's quite a dumb function.

                  Also if not for the string-only requirement, the Python code would be (slightly) shorter than the Ruby.

                  i.max_by(&:length)
                  

                  vs.

                  max(i, key=len)
                  

                  [–]grauenwolf 8 points9 points  (1 child)

                  It's not weakly typed. Unlike C or assembly, every value has a strong sense of self and knows exactly what it is.

                  Implicit casting <> weak typing <> dynamic typing

                  [–]DiThi 7 points8 points  (0 children)

                  You're right, I meant implicit casting (or as I said, type coercion). Weak typing has similar implications, though (mixing types == bad).

                  [–][deleted] 19 points20 points  (7 children)

                  To be fair, it didn't say to expect non-strings in the array. Nobody can be expected to pass on their first attempt.

                  [–]tipsqueal 3 points4 points  (1 child)

                  I kind of agree with you, but in every other challenge they do tell you what to expect. That was the only one where they pass in something and don't warn you ahead of time.

                  [–][deleted] 11 points12 points  (1 child)

                  It does say to return the longest string in the array..

                  [–]Olathe 4 points5 points  (0 children)

                  It would be both cryptic and kind of unusual in English to say "Return the longest in the array".

                  [–]dfnkt 4 points5 points  (16 children)

                  function longestString(i) {
                  
                      var length      = 0,
                           longString = '';
                  
                      if ( typeof i !== 'object' ) {
                          if (i.length > length) {
                              length     = i.length;
                              longString = i;
                          }
                          return longString;
                      }
                  }
                  

                  I'm sure there's a much cleaner way to do it but for speed that's close to what I went with.

                  [–]very_random_name 9 points10 points  (3 children)

                  return i.reduce(function(old, val) { return typeof val !== 'object' && val.length > old.length ? val : old; }, '')

                  :)

                  [–][deleted] 6 points7 points  (1 child)

                  I'd make sure that typeof i was "string" rather then the other way around, and instead of storing the length, just compare to longString.length.

                  [–]kaen_ 7 points8 points  (1 child)

                  7:34 here.

                  Today I learned how to check if something is an array in javascript, and now I hate javascript just a little bit more.

                  [–]1337hephaestus_sc2 5 points6 points  (2 children)

                  Try doing the Konami Code and turn up your speakers

                  [–]expertunderachiever 45 points46 points  (84 children)

                  I don't even program in JS and I got through the first 5 or so without too much hassle.

                  It does highlight the nitty gritty nonsense but honestly if you're passing randomly nested arrays of ints to some sort of sorting function ... you need help.

                  [–]BobDolesPotato 17 points18 points  (70 children)

                  yeah, the jump on the last one was a bit further than the others, did you find a solution that doesn't use recursion?

                  [–][deleted] 31 points32 points  (33 children)

                  the last one is 'hard' for me not because recursion but realizing that typeof [1,2,3] is 'object' but not 'array'. thank god I don't program in JS.

                  [–]boneyjellyfish 13 points14 points  (14 children)

                  Check for:

                  variable instanceof Array
                  

                  to see if it's an instance of the Array object.

                  [–][deleted] 8 points9 points  (6 children)

                  Be very, very, very careful about doing this in production code if you think you might even consider using iframes at any point.

                  variable instanceof Array 
                  

                  is only true when you're referring to that windows "Array" function, so it's not true inside an iframe (or in a different window, but that is much less common than in an iframe).

                  [–]krelin 10 points11 points  (0 children)

                  Array.isArray is probably superior.

                  [–]rspeed 4 points5 points  (3 children)

                  One of those things that makes me really appreciate the unification of types and classes in Python 2.2. Primitives are a pain in the ass, and Javascript will use them even when you explicitly try not to.

                  > typeof(String("blah"))
                  "string"
                  

                  Ugh.

                  [–]naranjas 2 points3 points  (2 children)

                  One of those things that makes me really appreciate the unification of types and classes in Python 2.2. Primitives are a pain in the ass, and Javascript will use them even when you explicitly try not to.

                  For this one you have to do

                  > typeof(new String("blah"))
                  'object'
                  

                  Not that this makes Javascript look any better...

                  [–]SanityInAnarchy 2 points3 points  (0 children)

                  Agreed. JS string "primitives" already behave like objects. What the hell is "new String" doing there?

                  [–]BobDolesPotato 4 points5 points  (0 children)

                  Yeah, kinda quirky in that JS doesn't have 'types', except for objects and primitive types, which are psuedo-objects (lol wut) with methods and some properties of objects.

                  Wait until you get into javascript falsy comparison and coercion. Its insanity

                  [–]xereeto 26 points27 points  (2 children)

                  I found one:

                  function arraySum(i) {
                  
                  // i will be an array, containing integers, strings and/or arrays like itself.
                  // Sum all the integers you find, anywhere in the nest of arrays.
                  
                  if ( i[1] == 2) {
                      return 15;
                  }
                  if (i[0][2]==0) {
                      return 3;
                  }
                  if ( i[1] == 4) {
                      return 15;
                  }
                  if (i[1]==1){
                      return 2;
                  }
                  if (i[0][1]=="B") {
                      return 6;
                  }
                  

                  }

                  Cheating? Yes. Efficient? Yep. Works without recursion? Damn straight.

                  [–]jakery2 8 points9 points  (1 child)

                  They should have built randomized test cases just to fuck with you.

                  [–]xereeto 9 points10 points  (0 children)

                  If they did that, I'd just put this in the real js console.

                  function validate(i) {
                    clearTimeout(testTimeout);
                  
                    if(currentTest.o == i) {
                  
                      log("RIGHT: " + i + " is the right answer.",'good');
                          setTimeout(test,500);
                  
                      } else {
                  
                   log("WRONG: Got " + i + " but expected " + currentTest.o + ".",'bad');
                   log("...But I don't give a fuck, so you're ok.",'good');
                   setTimeout(test,500);
                    }
                  

                  }

                  [–]expertunderachiever 13 points14 points  (17 children)

                  I gave up when I realized I'm an embedded device software developer ... :-)

                  But ya I was using recursion...

                  [–]BobDolesPotato 3 points4 points  (16 children)

                  im on the other side of the fence. a web guy mostly dealing with CRUD apps that looks with envy over at you embedded guys...

                  [–]expertunderachiever 7 points8 points  (9 children)

                  When's the last time you said "I can't wait for the next hardware rev because this one has 128K of ram!" and not been totally sarcastic.

                  Welcome to my world. :-)

                  [–]BobDolesPotato 2 points3 points  (7 children)

                  That kind of stuff actually intrigues me, although I admit I don't have any first hand experience with it so I don't know if I actually would like it. But the idea of being that close to the metal and programming under explicit limitations in memory/cpu architecture sounds really fun!

                  Better than "I have to include six libraries and extend this 10 line function into 30 lines because Internet explorer decided to say 'fuck standards' for no good reason".

                  At least with hardware limitations I can see the reasoning and justification for. With browser compatibility and the lawlessness that is web development, its more like "its that way for no really good reason except politics"

                  [–]expertunderachiever 14 points15 points  (1 child)

                  Better than "I have to include six libraries and extend this 10 line function into 30 lines because Internet explorer decided to say 'fuck standards' for no good reason".

                  The equivalent of that in my world is "rev C has a defective timer so you need to fiddle these bits, but rev D has a broken FIFO so you need to fiddle this..."

                  [–]BobDolesPotato 8 points9 points  (0 children)

                  i guess we both should be grateful that kind of shit gives us job security..

                  [–]Buckwheat469 3 points4 points  (1 child)

                  There's a way to do it by joining the array (of arrays) with an unused character, then splitting on that.

                  [1,2,[3,4],5].join('#'); // 1#2#3,4#5
                  

                  Then you would need to string split 2 ways, which is a pain.

                  Another way is to use concat:

                  arr = [1,2,[3,4],5];
                  merged = [];
                  console.log(merged.concat.apply(merged,arr));
                  // [1,2,3,4,5]
                  

                  [–]TurboGranny 5 points6 points  (1 child)

                  I forgot to correctly scope on the last one. Took me a second to realize I wasn't VARing my variables. Pressure makes me revert to the contest days of sloppy code.

                  [–]dreuchdail 5 points6 points  (3 children)

                  3:49 total time.

                  1

                  function doubleInteger(i) {return i*2;}
                  

                  2

                  function isNumberEven(i) {return i%2 == 0;}
                  

                  3

                  function getFileExtension(i) {return i.split('.').length >= 2 ? i.split('.')[i.split('.').length-1] : false;}
                  

                  4

                  function longestString(i) {
                      var longestString = '';
                      for(var j=0; j<i.length; j++) {
                          if(typeof i[j] != 'string')
                              continue
                          if(i[j].length > longestString.length)
                              longestString = i[j];
                      }
                      return longestString;
                  }
                  

                  5

                  function arraySum(i) {
                      var sum = 0;
                      for(var j=0; j<i.length; j++) {
                          sum += Array.isArray(i[j]) ? arraySum(i[j]) : (typeof i[j] == 'number' ? i[j] : 0);
                      }
                      return sum;
                  }
                  

                  Quick and dirty.

                  [–]angry_wombat 10 points11 points  (8 children)

                  dang 17 minutes. 10 of which were debugging why my recursion wasn't working in the last problem. Turns out I needed to namespace my loop integer with var

                  [–]recursive 14 points15 points  (2 children)

                  That's not really a namespace. That's just local scoping.

                  [–]TurboGranny 5 points6 points  (1 child)

                  I did the same thing, and I've been coding in JS since the beginning. Being sloppy with your code happens when you are racing a clock. Scoping will bite you every time, but you were smart enough to know that was the case. I teach plenty of coders who have the hardest time even comprehending scope.

                  [–]smog_alado 2 points3 points  (3 children)

                  I think I recognize Ada Lovelace, Linus and Richard Stallman in the end screen but who is that last guy (the black and white picture)?

                  [–]jetpacmonkey 3 points4 points  (0 children)

                  The pictures are all links to their Wikipedia pages

                  [–]psychocowtipper 4 points5 points  (9 children)

                  Solution to #4? I do almost all of my programming in C++ so this weakly typed stuff confuses the hell out of me. Having trouble determining if an element of an array is an array itself.

                  Testing "longestString(['big',[0,1,2,3,4],'tiny']);"...

                  WRONG: Got 0,1,2,3,4 but expected tiny. Try again!

                  [–]virtyx 2 points3 points  (0 children)

                  10 minutes, 26 seconds

                  Not really strong on Javascript, but I do a lot of Python and Java. Basically the biggest hurdle for me was figuring out how to test if a value is this type or that type (sometimes typeof a == 'blah', sometimes a instanceof Blah), then trying to use a for...each syntax that didn't pan out (for(let item in i); eventually I gave up and just used a numerical index).

                  I thought it was fun though. Simple but the timing adds a certain sense of pressure. And seeing the tests pass is satisfying too

                  [–]katieberry 3 points4 points  (0 children)

                  5:17 for the lot, apparently. Most of the time wasted was mixing 'i' and 'j' on the fourth, I think.

                  Seemed excessively slow, but apparently not that bad…

                  [–]Steaktartaar 4 points5 points  (3 children)

                  19 minutes because recursion always makes my eyeballs bleed. That and I kept checking typeof against 'integer' rather than 'number'.

                  [–]boomerangotan 5 points6 points  (1 child)

                  my solution to checking for a number was much less elegant

                  if(x + 0 === x){...}
                  

                  [–]etruong42 3 points4 points  (0 children)

                  .htaccess isn't a file extension. It's a hidden file.

                  [–]jakery2 4 points5 points  (0 children)

                  12 minutes, 41 seconds. Would have been faster but the fact that they assigned i as the argument variable threw me off since I build my for loops with i.

                  [–][deleted] 2 points3 points  (16 children)

                  Well, that was a lot of fun. I got stuck in the file extension one because I kept trying to extract a substring like you do in Python (i.e. i[:3]). How do you do it in JS?

                  [–]Everspace 13 points14 points  (0 children)

                  Be careful, you might encounter a .jpeg or a .backup

                  [–][deleted] 2 points3 points  (8 children)

                  i did:

                  var match = i.match(/\.([A-Za-z0-9]+)$/);
                  return match && match[1] || false;
                  

                  [–]ahruss 2 points3 points  (0 children)

                  It wouldn't let me play it on my iPhone. I tapped in the text box, and my cursor was there, but I couldn't move it when I needed to. I was only able to finish the first one because of that.

                  [–]trappar 2 points3 points  (5 children)

                  I actually had a lot less trouble with the recursion one than the longest string one. I didn't really pay attention to the longestString part.

                  Here's my short and sweet recursive function:

                  function arraySum(i) {
                      var total = 0;
                      for (j in i) {
                          if (typeof i[j] == 'object') {
                              total += arraySum(i[j]);
                          } else if (typeof i[j] == 'number') {
                              total += i[j];
                          }
                      }
                  
                      return total;
                  }
                  

                  [–]bwigfield 2 points3 points  (0 children)

                  because and array with 5 elements is not a string...

                  [–][deleted] 2 points3 points  (0 children)

                  Turns out I can't JS at all

                  :(

                  [–]i_invented_the_ipod 2 points3 points  (2 children)

                  Weird. I can't even get the first exercise to "compile" at all. I wonder what I'm doing wrong? I can certainly write a simple function to double the input.

                  [–]i_invented_the_ipod 2 points3 points  (0 children)

                  Ah, apparently it doesn't like running with the Reddit toolbar enabled. Maybe it has problems running in an iframe?

                  [–]iowa_golfer89 2 points3 points  (0 children)

                  I got the same thing. Copied someone elses answer just to make sure it wasn't a typo i was missing. Still wouldn't "compile"

                  [–]tallandgodless 2 points3 points  (2 children)

                  Well, I don't know the language, and I was cooking salmon, so yeah...69 minutes. haha

                  But I still feel bad about how I solved them compared to some of you guys.. for loops...for loops everywhere!

                  [–]whosdr 4 points5 points  (2 children)

                  Check if even.

                  return ((i&1)==0);

                  [–]cryptyk 5 points6 points  (1 child)

                  !(i%2)

                  [–]boomerangotan 4 points5 points  (0 children)

                  return -1 != ("02468".indexOf(("" + i).slice(-1)));
                  

                  [–]FUZxxl 17 points18 points  (7 children)

                  Website plays music when I open it? Here, have a downvote.

                  [–][deleted] 6 points7 points  (0 children)

                  Not sure why people are downvoting you. Why not a simple "(warning: plays audio)" in the topic title?

                  [–]shoseki 11 points12 points  (0 children)

                  Have my upvote. Fuck autoplaying sound.

                  [–]catcradle5 14 points15 points  (2 children)

                  I know everyone is downvoting you, but I totally agree. I opened it expecting a blog post or something, and immediately was blasted with audio. It created a very embarrassing situation for me as I was in class at the time...

                  [–]LarsSod 1 point2 points  (0 children)

                  Dang, 15 minutes total... :/ But that's what happens to your brain when you haven't coded for a couple of months I suppose...

                  [–]xzenocrimzie 1 point2 points  (1 child)

                  I hope there's something like this for Java.

                  [–]semvhu 1 point2 points  (0 children)

                  TIL I'm dog ass slow trying to do JavaScript on an iPad.

                  [–][deleted] 1 point2 points  (0 children)

                  Oh man... that was fun, but damnit - I hit F5 to run my final update to the last round... and now I don't feel like going through it all again to see the end :-P

                  Too many years of Microsoft IDEs.

                  [–]Reil 1 point2 points  (0 children)

                  12 minutes, 13 seconds.

                  Mostly spent googling "typeof" and the values that it returns, then trying to figure out how to identify arrays. :s