Shiftin', Unshiftin', Pushin' n Poppin'
I would like to show a neat trick on looping through arrays, not using one value every time but sometimes one, sometimes two and so on.
I found this while doing the Bowling Game Code Kata. A kata is like a code practice, you try to solve a problem in many different ways to see what you find. I find this very interesting, cause I'm learning test driven development at the moment, and it's perfect to try different implementations once you got your tests set up.
A guy named Zach Leat has set up a very nice repository of javascript katas, and I will show you part of his Bowling Game, very true to the original Java implementation:
What you see above is the "score" function, the way the bowling scores are summed up. As you see, when you hit a strike, you use one value from the array, and then you add up the following two but not passing by them. When you hit a spare, you use two values from the array, and then adding one following value, without passing by it.
A nicer way of doing this, without having to deal with a counter variable, is simply shifting the array. That way you don't have to count, because you always use the latest values, like this:
The shift, unshift, push and pop functions are really great for working with arrays, though i have to admit it took me long to memorize. I think most people know push and pop. Here's an overview:
Hope that helps with something! Anyway if you sit on any good code katas, i would really appreciate if you post them in the comments! Looking forward to it!
PS. Here's my entire bowling score kata, if you find it useful!