Today in class we were talking about the FizzBuzz question and if it can be solved with no conditionals or for loops.
So in C++ there’s something called goto, which acts like a loop without actually being one. If you look at the documentation for it, Dijkstra (of shortest path algorithm) wrote an essay about it titled “Goto Considered Harmful”. Which should really tell you enough about why you shouldn’t use it. But for funsies I did:
To be honest, most people start solving this problem with an if/else statement and a loop. So switching to JavaScript I did just that.
From there I decided to refractor it to a ternary because I love me some nested ternary. It makes most people’s eyes cross, but there’s something about nested ternary that when formatted correctly, looks so effortlessly clean.
Moving on, I went ahead and researched what other people did to try and solve the algorithm without if/else statements. Quite honestly in my previous FizzBuzz solves I'd never gone that far down the rabbit hole so I started off with a Medium article by Michele Riva, and ended up at a Dev.to article by Keff.
Looking through the examples opened my mind to how I might get around needing if/else or || and && to check each element. I blatantly stole having three checks in separate functions, but then researched using replace() with RegEx. And although it seems like you can do it, I wasn’t able to push it through, mores the pity.
From there I switched to finding the index so I could see about replacing the element. And that was when I stumbled on the MDN documentation for findIndex();
I had never used findIndex() with a function inside of it before. So I paired it with splice() and tested it out - and it worked.
My solution:
- Three separate functions checking to see if the element is divisible by 3, 5, or 15.
- Creates an array filled with ascending elements 0 through N.
- Removes the zero element with shift().
- Runs a for loop to find the index of each element that is divisible by 3, 5, or 15 using findIndex().
- Uses splice() to remove it and replace each element with “FizzBuzz”, “Fizz” or “Buzz”.
After confirming by comparing it against my other previous solves I was left with the same feeling I get when I do something totally random to solve a problem. “It works!... But why would you ever do it that way.”
So yes, FizzBuzz with no if/else. But why would you ever do it that way.
Top comments (0)