Solving a simple problem with Underscore
When I first saw Reaktor's recruiting puzzle I knew had to try it. It introduced simple, yet bit painful to implement with vanilla javascript and encouraged utilizing Underscore.js library. They would contact only if you could solve problem in a elegant way.
Anyways they provided string length of 1000 characters. There you have to find the highest multiplication of set of 5 numbers. Implementation must be done in javascript, easy isn't it? This is almost like world famous Fizz buzz test for programmers.
There is nice online editor on page where you can write your solution and you get green light when you find correct number. I used it for getting input string since I really like development tools I have on my laptop.
First I started with simple alert(input); to verify they won't screw with me.
Everything seems to be in order. Convert to numbers, loop through numbers and calculate highest group of five. Or just write "return xxxxx;". It would be the most elegant solution after all, right?
My first try was vanilla javascript described above, it turned out to be one ugly for loop -- doing multiplication and variable keeping the highest number. Nothing really interesting there.
I was really keen to see if Underscore could solve problem more elegant way. After reading documentation a bit, it turned out to be really nice little library for handling collections and arrays. A real gem of the library is at the bottom of the documentation - .chain, but more about it later in this post.
https://gist.github.com/mrasanen/6710723
First refactoring (above) was more into utilizing Underscore, but it was still ugly and reminded vanilla javascript I wrote earlier. Also make note multiplication is done with indexes and static numbers. You would hit a problem if calculation logic is changed even a bit.
https://gist.github.com/mrasanen/6724953
Second refactoring (above) was more into chaining and slicing and dicing number groups. Code looks similar to LINQ queries in C# and it's not really a bad thing. All of console.log(); methods removed before script actually pasted to Github. And now, after 4 weeks I wrote that, I'd do it in different way, but code is readable and you figure out what it does in seconds.
Thank you Reaktor for making great problem to solve and inspiration. I'm sorry I didn't email my solution to you, Maybe next time :)
Bottom line is that they really know programmers are into solving problems and learning new things around their craftmanship. At least I found good utility library and learned a bit how to use it and when. But this puzzle got me curious about functional programming in javascript and that's why I bought this book: Functional JavaScript: Introducing Functional Programming with Underscore.js So far it has introduced me another world. Great book.
ps. My first tries with Underscore were a mess -- tried using .groupBy but it wasn't what I needed..
















