15 02 2010
JavaScript Quiz: Challenge your brain
“Everything old is new again”
Info: I’ve posted this javascript quiz almost two years ago. Unfortunately I’ve got some problems with host and this quiz was not available anymore. I still like this challenge, that’s why I decided to repost it again.
Introduction
I always enjoy programming JavaScript, it always brings me some new and interesting puzzles. I was explaining functions in JS to a friend and got realized that itโs a really great language with its flexibility, closures, anonymous functions, first-class functions etc. Even the stupid idea that you can write a function by calling it an unlimited number of times is simply amazing.
Example:
fnc()()()()()()()()();
Challenge
Further thinking gave me the idea that it would be nice to have this function do something more weird and confusing. This useless function should give as the output the number of times it has been called (for example in alert box). The challenge of this puzzle is that it must give output only at the end of the execution, with the last call.
That means that code like that fnc()()()()()()()
MUST show one alert box with text โFnc called 7 timesโ.
After some experiments I found a solution for this puzzle and I figured that you might also want to challenge yourself by finding out the way it can be done. So, I propose everyone to post their solutions in the comments.
Solution
Try it live :
(Execute)
If you decided that itโs enough for you to break your head with this puzzle, you can always check my solution (in html code ๐ ).
I hope you liked my idea, and also get enthusiastic, like I did, when I was searching for the answer.
The original entry was posted on Saturday, July 12th, 2008 at 4:12 pm
JavaScript without “new” and “this”keywords Focus, tabIndex and behavior of browsers
Great quiz ๐
My first try was to create a curried function, but then i realized that i would never know when the function was finished, so i came up with the following function, which uses some kind of threading, by setting a timeout, it delays an anonymous function until the current calls are completed. f.max is a ‘static’ variable which is available accross all invocation of f. i and its current value however are hitched in the scope of the anonymous function. So only for the last instantation/ call of this function the scope of the function wil hold the proper ‘i’, resulting in the proper alert message.
f()()()();
@Michel Weststrate
Good solution ๐ I like this creative approach by checking i == f.max ๐
In my opinion knowing different solutions to one problem extend your view to the language.