Settings

Theme

You Can't JavaScript Under Pressure

toys.usvsth3m.com

72 points by jgv 12 years ago · 109 comments

Reader

mikeash 12 years ago

Thanks for immediately playing audio without asking me first. I know everybody just loves it when web pages do that.

  • corresation 12 years ago

    Because of your comment, HN will have a dozen "I am so disappointed in all of you" posts in the coming week declaring how mean everyone here is, and how it is no longer like it "once was".

    I hope you are happy.

    • mikeash 12 years ago

      I'd be happier if this page hadn't blasted music into my conference call.

      • tutuca 12 years ago

        Your fault for not paying attention during a conference call...

        • mikeash 12 years ago

          Yeah, because we never have conference calls where we have to be there but don't really have to do anything besides listen for our name.

      • Demiurge 12 years ago

        Hehe. I wish OSX had individual program volume controls... On Windows 7 I usually have flash process volume on 'off', unless I'm specifically watching something.

      • codenberg 12 years ago

        don't surf the web on a conference call. problem solved.

      • enraged_camel 12 years ago

        Sounds like a personal problem.

    • skrebbel 12 years ago

      I love how you're mocking HN and the parent post at the same time!

      • corresation 12 years ago

        I'm actually not mocking either the post or HN. If I am being a little snarky, it is towards the thin skinned who zero in on any comment they don't like and then launch a tirade in hopes of, essentially, group bullying. It happens with increasing regularity.

        • asveikau 12 years ago

          I actually find it refreshing when people mock or criticize HN on HN. There is too much orthodoxy here, too much defensiveness when that orthodoxy is questioned, too much indirection where a plainly stated opinion would suffice, and a lot of people don't have a sense of humor about themselves. (Watch this get downvoted by people proving exactly my point.)

  • buckbova 12 years ago

    If using chrome, the Chrome Toolbox has a handy mute all tabs feature. I have it muted by default.

    https://code.google.com/p/chrome-toolbox/

tomscott 12 years ago

Oh! Hello. This is my thing I made for usvsth3m.com. Hope y'all like it. HTML5 Webworkers made it possible - sandboxing user-submitted JavaScript so an accidental while(1) or document.write can't kill everything.

Do have a look at the source code. Oh, and try turning up your speakers and typing in the Konami code...

  • TazeTSchnitzel 12 years ago

    Oh, you, Tom Scott, made it? :D I'm a big fan.

    A few suggestions, then:

    1. Don't use i as the name of the parameter. A lot of people use that as the name of loop variables, and it means breaking habit or wasting time changing the name.

    2. For test 3, try some multiple-extension files to make sure they did it right (some.file.multiple.extensions, should return "extensions")

    3. For test 5, it says "integers". Try some non-integers during testing, to make sure that it's only checking for integers.

    4. For test 5, it says "arrays". Try some objects to make sure they're not being lazy and using typeof thing === "object"

    Anyway, thanks for making this. I love it!

  • JosephRedfern 12 years ago

    If you alert() something inside an infinite loop it doesn't seem to be able to detect it (nor does it show an alert box!)

peeters 12 years ago

Fun distraction. For me it was:

30% figuring out the answer, 20% not having my editor shortcuts available, 50% figuring out how to check if a value is a certain type.

Am I the only one that gives their functions preconditions that the input is good? To me, throwing up when you're passed a non-number to a sum method is correct behavior.

ryanthejuggler 12 years ago

Could there be a histogram at the end that shows distribution of finishing times? Or at least a leaderboard... I did pretty well [obviously ;)] but I'd like to see where my time falls in relationship to others.

I've confirmed that I can, in fact, code under pressure, but to what degree?

Other than that, fantastically fun game. My only regret is that it's a one-time game by nature, since obviously the second time around you'd simply be remembering what you did the first time instead of creating it.

cheshire137 12 years ago

The sudden music/talking that started was annoying and caused me to close the tab immediately.

  • brudgers 12 years ago

    No NoScript?

    • tonyarkles 12 years ago

      Maybe I'm naive but... I suspect that the rest of the page wouldn't have worked with NoScript. Since you're, you know, typing in JavaScript code and running it against some test cases.

      • ronaldx 12 years ago

        I am using Noscript and the page works fine:

        - usvsthem is white-listed so Javascript runs, which is all that's strictly required.

        - White-listed sites are still blocked from running plugins including <AUDIO>. It's straightforward to override this on a plugin-by-plugin basis but I typically don't want to.

        11:14. The 14 seconds were enough for the first two questions, but I find strings and array handling tough when switching languages.

    • Kiro 12 years ago

      Are you seriously using NoScript? I thought it was a myth.

jenjem 12 years ago

I took almost 40 minutes, am I in the wrong profession? I figured out how to do all of them right away but I got stuck on figuring out JS syntax in a few places since I barely ever use it and felt like googling was cheating. I did use google on the last one to see how to check if something's an array. I even ended up checking at one point if something's a number by (!isNaN(n/4) && n+n == 2*n), and checked for being a string or not with if(s.length!=undefined) (I know that returns true for an array as well). Would've been a lot easier with something like Intellisense - coding without it feels almost like I'm blind, after being used to it. That and I thought alert() didn't work until I noticed at the end it actually sent it to the output.

kirse 12 years ago

Fun little puzzles. First 4 went pretty quickly (~8:00) and then the last one took ~7 minutes Googling around for this so I could test if a variable was an integer...

  n===+n && n===(n|0)
Wish I could see my answers after the fact though!

Edit: Read the initial requirements of the puzzle, it says sum all the integers, not all the numbers. People using (typeof i[x] == 'number') just got lucky because the test-cases didn't exercise the full requirements of the puzzle ;)

  // i will be an array, containing integers and/or arrays like itself.
  // Sum all the integers you find, anywhere in the nest of arrays.
  • downtowncanada 12 years ago

    if(typeof i[p] === typeof 3){//it's an int

      sum += i[p];
    
    }else if(typeof i[p] === typeof [3]){//it's an array

      recursion(i[p]);
    
    }

    pretty simple no?

    • cs02rm0 12 years ago

      That would've been simpler, but I seemed to get away with typeof(i[p]) === "object" and typeof(i[p]) === 1*typeof(i[p]) to test if it was an int.

      I dread to think what obscure code I've left behind.

    • chrisrhoden 12 years ago

      no, in this case the first will match on all numbers and the second will match on all objects.

      You should learn a little more about JS before you call this simple.

  • kentor 12 years ago

        n % 1 == 0
  • Justin_Time 12 years ago

    typeof n === 'number'

    It didn't actually require differentiating between integers and floats, just numbers and other types.

    • iainnash 12 years ago

      This typeof stuff (and having number instead of integer, string, etc) was the hardest part of this for me.

      Normally javascript function inputs aren't this messy.

    • solox3 12 years ago

          > typeof 5.4
            "number"
      • kirse 12 years ago

        Yea, this is what I realized once I saw the puzzle was throwing junk data like "false" on #5.

        I mentally skipped over Justin_Time's solution, figuring I would just hit a float error case because it was going to be a stickler about integers.

  • chrisrhoden 12 years ago

    n===~~n

Demiurge 12 years ago

That was fun! I just got in to work so I was properly sleeping. I also rarely use typeof, so I had to look up that 'integer' and 'array' do not exist :) Also, what was really annoying is the use of 'i' for the argument. That's what I exclusively use for the 'for loop' index! Tripped me up a lot, I had to consciously remind myself every time I accessed the array. Last 'also', the font is WAY too big for my small screen, the comment never fit in, I had to scroll... So I think I did bad, 12 minutes. But still fun :)

  • robflynn 12 years ago

    The use of 'i' set me back a bit, too. Caused me to go into an infinite loop at one point.

    • daGrevis 12 years ago

      Exactly this. I had to rename `i` for indexes to `j` and that really messes my head up! :(

Bahamut 12 years ago

It was a kinda cool thing, although I got some strange behavior when I was using `match` for determining whether the input is a filename - my regex was /.\../ (and so I did var match = i.match(/.\../) ), and match[1] was undefined - turned out match[2] was what I wanted, and it was present, but the behavior was incorrect in the reporting console in the game.

I finished this in 4 minutes.

Edit: looks like HN doesn't like asterisks

  • tensafefrogs 12 years ago

    I thought regex was overkill for that one and used:

    return input.split(".")[1] || "";

    • dclowd9901 12 years ago

      I fully anticipated a test case like file.name.ext. Of course, you could still do what you're doing, but it'd be a lot more verbose.

    • Bahamut 12 years ago

      What if it had multiple dots? Anyhow, I am on 5 hours of sleep, and already s spent6 hours coding...I just wanted to finish fast.

prezjordan 12 years ago

Lighten up, everyone, this is a fun little thing. Thanks for sharing.

ianstallings 12 years ago

I'm a bit disappointed that it doesn't award points for my heavy use of regex and obscure variable names.

  • Cyranix 12 years ago

    > obscure variable names

    Absolutely! Being under the gun led me, at one point, to have a "longest string in array" method with a statement like

      if (i[z].length < qq) { ... }
metaphorm 12 years ago

there's a truly dubious test case in the File Extension test.

file called .htaccess is not filename "" and extension "htaccess" with a "." separating the two. .htaccess is a unix style dotfile. its whole name is ".htaccess" and it has no file extension.

  • taternuts 12 years ago

    I have to admit to cheating and putting 'if (i === '.htaccess') return 'htaccess';' to save time :)

    • jrawlings 12 years ago

      I just did

      return i.indexOf('.') > -1 ? i.substring(i.indexOf('.')+1) : false;

      Seemed to pass all test cases

      • EdgarVerona 12 years ago

        Aye, I did similarly, though for some reason I did >= 0 instead of > -1. I wonder what % of people choose one test approach vs. the other?

pak 12 years ago

It's problems like 5 that make me sad that IE <9 doesn't have Array.prototype.reduce.

    return i.reduce(function(prev, next) {
        if (typeof(next) == "object" && next.length) { return arraySum(next) + prev; }
        if (typeof(next) == "number") { return next + prev; }
        return prev;
    }, 0);
Something that simple needs to be shimmed on earlier IEs. In fact, I had to look up Array.prototype.reduce for this since I usually use Underscore's. Javascript problems...
  • 1wheel 12 years ago
    • pak 12 years ago

      Cool project, but all the warnings on that page about the edge cases make me concerned about trying to exuberantly move to ES5, and so I just stick with Underscore and the same level of JavaScript syntax I've been writing since 2005. (sigh)

  • dmak 12 years ago

    Pretty interesting solution. The first thing that came to my head was a loop, but you just used reduce. What are some scenarios where you would use a reduce over a loop? I use underscore a lot too, and I find myself just using _.each all the time

    • pak 12 years ago

      Anytime where you are trying to "collect" features of an array into one final value, and the collection function can be sensibly applied to the elements in any order as long as some interim value is passed along (e.g. summing, maximizing), the reduce paradigm is appropriate and can be more readable.

      The bonus upside is that these paradigms also make parallelism quite simple, should it later be necessary.

drdrxp 12 years ago

The input argument name "i" is really annoying. I always use "i" as for-loop var. Made some mistake on this. But the Game is really great. :D

dmak 12 years ago

I got 11 minutes and 14 seconds. Is that slow? The answer to my last solution was like this:

      function arraySum(i) {
	var total = 0
	for(var x=0; x < i.length; x++) {
		if(typeof i[x] == 'object') {
			 arraySum(i[x])
		} else if(typeof i[x] == 'number') {
			total += i[x]
		}
	}
	return total
     }
  • lighthazard 12 years ago

    ~6 minutes and 30 seconds

    That was also my final answer. However, I was going for speed and not elegance, after looking at other people's responses with prototypes and all.

  • dclowd9901 12 years ago

    You must've total+= arraySum(i[x]) right? Otherwise this couldn't work as the result of a deep dive wouldn't be utilized anywhere...

    • dmak 12 years ago

      Yeah, I did, thanks for pointing that out. I made that mistake when writing the comment.

  • ep103 12 years ago

    you made the same mistake I did at first. Corrected below.

    function arraySum(i) { var total = 0 for(var x=0; x < i.length; x++) { if(typeof i[x] == 'object') { total += arraySum(i[x]) } else if(typeof i[x] == 'number') { total += i[x] } } return total }

peregrine 12 years ago

Total bait and switch. As soon as I saw that random array in my array of strings I knew what kind of game this would be.

hcarvalhoalves 12 years ago

Last one reminded me how awful JS is once again. There are 5 different ways to check if an object is an array, some are implementation dependent, and the obvious one doesn't work (typeof x == "array").

  • hayksaakian 12 years ago

    typeof(x) === typeof(["something which is certainly", "an array"])

    or am i missing something?

    • wging 12 years ago

           > typeof ["a", "b"]
      
          "object"
      
      Of course, since you're told you'll only get numbers, arrays, and strings, that is enough to solve the problem narrowly.
  • Bahamut 12 years ago

    x instanceof Array

salehenrahman 12 years ago

I created a CoffeeScript version of it. http://shovon.github.io/youcantcoffeescriptunderpressure/

axyjo 12 years ago

"6 minutes, 21 seconds for all 5 levels. Well done!" I feel like I should have done better considering JS is one of my primary languages.

jamesroseman 12 years ago

9:10, had to Google a bit for type checking, and I had forgotten the proper syntax for a string split. :-/

salehenrahman 12 years ago

I got 3 minutes 39 seconds.

I used i.forEach for questions involving arrays, instead of for-loops. Saves me time.

leehro 12 years ago

This was awesome. 5:48. I actually turned my sound on for the end.

chudi 12 years ago

nice stuff but this is plain wrong! // return the file extension (with no period) if it has one, otherwise false

its like returning error codes in C for errors

ep103 12 years ago

What's everyone's times? I did 7 minutes

  • oftenwrong 12 years ago

    8:30

    Spent nearly the entire time on #3 because I was trying to use String.replace to work and failing. Ended up using .split instead, which passed thanks to poor test coverage (just like at work!).

  • EdgarVerona 12 years ago

    8:11 for me - as it sounds like was the case with others, the majority of that time was searching for how to check for specific types in Javascript.

    For the "is this actually a string?" check, for example, I started looking for the existence of the match method on the object, which of course would have failed if they passed some random object with match defined so I cheated a bit. I'd like to see the full breadth of test options people took out there.

  • methodover 12 years ago

    14 minutes, 27 seconds for all 5 levels. Bah, should've done better. On the other hand I just woke up.

    I wanna see one of these in Python.

  • hatsuseno 12 years ago

    My JS is somewhat rusty, glad I had a .map() to work with. 9 minutes something, I did 'cheat' by looking up some typeof returns.

  • dpedu 12 years ago

    6:11.

    Blew through the first 4 but spent half my time on the last one because I don't have Javascript type checking memorized.

  • robflynn 12 years ago

    "2 minutes, 32 seconds for all 5 levels. Well done!"

    The "kill screen" song is stuck in my head now.

  • nakovet 12 years ago

    I only did one time: 8 minutes and 57 seconds, for sure the next try will be way easier.

  • myh 12 years ago

    5 minutes, 31 seconds for all 5 levels. Well done!

  • Justin_Time 12 years ago

    4 minutes, 56 seconds for all 5 levels. Well done!

  • dmak 12 years ago

    11 minutes 14 seconds. I wish I did faster!

  • CompelTechnic 12 years ago

    17 minutes, 47 seconds. slow poke here.

  • mneary 12 years ago

    Just under 3 minutes!

  • Demiurge 12 years ago

    12:45

  • renekooi 12 years ago

    2:26.

  • trevordixon 12 years ago

    4:20.

  • ryanthejuggler 12 years ago

    3:15

Kiro 12 years ago

Would be great to see some solutions.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection