DEV Community

Nathan Kallman
Nathan Kallman

Posted on • Updated on • Originally published at kallmanation.com

Unconditional Challenge: FizzBuzz without `if`

As the title says, make a classic FizzBuzz function or method without using if/else (or equivalents like ternaries, ?:, sneaky).

Specifically:

  1. The function should accept one argument, assume it will always be a positive integer.
  2. The function should return a string (or something coercible into a string in loosely typed languages) according to the following rules:
    1. If the given number is divisible by 3, then return Fizz
    2. If the given number is divisible by 5, then return Buzz
    3. If the given number is divisible by both 3 and 5, then return the combination FizzBuzz
    4. If the given number is none of those things, then return the given number

The expected outputs for the first fifteen numbers in order is:

1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz
Enter fullscreen mode Exit fullscreen mode

Hard mode

Do this without "secret" conditionals like || and && (in loosely typed languages like JavaScript) or null coalescing operators like ?? or null safe operators like ?. or &..

Also no looping constructs that could be abused into a conditional like while or for.

Hint number 1

I tagged functional on this post because functional programming can be used to solve this.

Hint number 2

I tagged oop on this post because the original object oriented concepts of message passing can be used to solve this.


Post below with your answers!

Think this is impossible? I'll post my own answers in both FP and OOP styles next week.

(If you were hoping for the next installment of my With Only CSS series, styling radio buttons, that's coming on Monday, follow me so you won't miss it!)

Latest comments (48)

Collapse
 
dannyengelman profile image
Danny Engelman

A bit late to the party...

Array(100)
  .fill((x, div, label) => x % div ? "" : label) //store Function in every index
  .map((func, idx) =>
    func(++idx, 3, "Fizz") + func(idx, 5, "Buzz") || idx
  );
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kallmanation profile image
Nathan Kallman

Welcome to the party!

Collapse
 
kallmanation profile image
Nathan Kallman

Very nice! I feel like this is actually pretty similar to my own Object-oriented approach (if you wanted to read):

Collapse
 
defenestrator profile image
Jeremy Jacob Anderson • Edited

Has someone done this yet? It's really very fast.
There's a ternary there, I admit.

function fizzbuzz(i) {
  let test = (d, s, x) => i % d == 0 ? _ => s + x('') : x
  let fizz = x => test(3, 'Fizz', x)
  let buzz = x => test(5, 'Buzz', x)
  return fizz(buzz(x=>x))(i.toString())
}

Array.apply(0, Array(100)).map(function (_, i) {
  i += 1
  return fizzbuzz(i)
}).join("\n")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kallmanation profile image
Nathan Kallman

Nice! But test uses a ternary ?: (which is just a different way to spell if in my opinion)

If you can get rid of that I think you'll have a solution!

Collapse
 
defenestrator profile image
Jeremy Jacob Anderson • Edited

I can't bring myself to be terribly interested in re-implementing language features like boolean or ternary. I loved seeing some of the really outlandish solutions like that un-sane RegEx that was posted. I enjoyed seeing the contortions done to avoid conditionals, too, but that's not something I'm into for it's own sake. I'm happy to fail at it.

There is a meaningful distinction between ternary and if.

if is a wilderness with few boundaries, as a form of Many-Valued Logic with an arbitrary number of values. Ternary is a specific subset of Many-Valued Logic; Three-Valued Logic. The Three-Valued Logic of ternary operators provides specific limitations that are not necessarily implied by the N-Valued Logic of the if statement. In most programming languages ternary is an operator, and if is a control structure block. Operators can be used in expressions, which is generally not true of if statements. Ternary is usually slightly computationally more expensive than if but has some advantages in terms of limiting complexity.

In real-world code I'm going to write an if (without else if or else if I can help it) about 95% of the time. It is both more readable and more performant in most cases. But when I need an expression that can make a decision between boolean and a maybe, I reach for ternary.

If you wanted to argue that switch is basically goto but potentially worse due to unintended fallthrough, then we'd have something to agree on.

The magic of the fizzbuzz problem is, of course, that it helps us understand in more granular detail that our design decisions, and design non-decisions, come with unavoidable trade-offs. It is a meditation on (a horrible term) non-functional requirements.

Collapse
 
alfrederson profile image
Alfrederson

How about this:

Collapse
 
kallmanation profile image
Nathan Kallman

Nice!

Collapse
 
indebanvdhamer profile image
Eric Nijman

This could probably get simplified (I've seen the one-liner of this one), but I still wanted to post mine

const fbMap = [
  () => 'FizzBuzz',
  String,
  String,
  () => 'Fizz',
  String,
  () => 'Buzz',
  () => 'Fizz',
  String,
  String,
  () => 'Fizz',
  () => 'Buzz',
  String,
  () => 'Fizz',
  String,
  String,
];
const fizzBuzz = x => fbMap[x % fbMap.length](x);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bashunaimiroy profile image
Bashu Naimi-Roy • Edited

I am posting for a friend who found some absolutely mind blowing ideas.

First a one-liner that extends my destructuring idea.

const fn = n => ({ ['2xx0x10xx01x0'[n % 15]]: result = n } = ['Fizz', 'Buzz', 'FizzBuzz'], result);
Enter fullscreen mode Exit fullscreen mode

secondly a solution built around a regex from hell/heaven

let fn = n => String(n).replace(/^(?=.*[05]$)(?:[0369]|[147](?:[0369]|[147][0369]*(?:[258]|[147][0369]*[147]))*(?:[258]|[147][0369]*[147])|[258](?:[258]|[258][0369]*(?:[147]|[258][0369]*[258]))*(?:[147]|[258][0369]*[258]))*$/, 'FizzBuzz').replace(/^(?:[0369]|[147](?:[0369]|[147][0369]*(?:[258]|[147][0369]*[147]))*(?:[258]|[147][0369]*[147])|[258](?:[258]|[258][0369]*(?:[147]|[258][0369]*[258]))*(?:[147]|[258][0369]*[258]))*$/, 'Fizz').replace(/^\d*[05]$/, 'Buzz');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bashunaimiroy profile image
Bashu Naimi-Roy

holy COW did I find out a lot of things about object destructuring while making this. Thanks for the challenge, Nathan. It was so great to notice how instinctively I reach for a conditional.

Collapse
 
kallmanation profile image
Nathan Kallman

I'm glad you liked it! I think its good to do a little self reflection on the way we do things every once in a while.

And WOW is that an impressive use of destructuring in JS. I knew about each of those things independently; I never have thought about putting them all together like that!

Collapse
 
bashunaimiroy profile image
Bashu Naimi-Roy

I'm thinking of an absolutely egregious version using try and catch, but I'm going to go ahead and assume that try/catch would be a "surrogate conditional"

Collapse
 
kallmanation profile image
Nathan Kallman

😂 it probably is, but now I want to see it implemented with just try/catch!

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited
function map(compare, say, next = v => v) {
    return function(value) {
        return [() => say, next][Math.sign(compare(value))](value)
    }
}
const process = map(
    v => (v % 3) + (v % 5),
    "fizzbuzz",
    map(v => v % 5, "buzz", map(v => v % 3, "fizz"))
)

for (let i = 1; i < 31; i++) {
    console.log(process(i))
}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
kallmanation profile image
Nathan Kallman

Well done! Clever use of Math.sign to select either the first or second element from an array

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

Slightly shorter without bothering to call out for variable potential conditions and using anons:


let map = (compare, say, next = v => v) => v => [() => say, next][Math.sign(v % compare)](v)
const process = map(15, "FizzBuzz", map(5, "Buzz", map(3, "Fizz")))

Enter fullscreen mode Exit fullscreen mode
Collapse
 
kallmanation profile image
Nathan Kallman

Happy Juneteenth! I love everyone's approaches here, it's fun to see the way each person thinks through the problem.

I'll be posting my answers on Monday (along with the next installment of With Only CSS) so encourage your friends to give this a shot over the weekend (or take another go yourself)!

Follow me and react with a 🔖 so you remember to come back and see what I post here.

Drop a 🦄 or ❤️ if you'd be interested in some follow up posts going more in depth into each (OO/FP) solution: how they work; how they are similar; and how they are different.

Thanks everyone who took the time to post a solution to my little challenge; I'll see you all on Monday!

Collapse
 
kallmanation profile image
Nathan Kallman • Edited

You can see both solutions in action on this codepen (planning one final post doing a compare/contrast between the two approaches)

Collapse
 
kallmanation profile image
Nathan Kallman

And here is my object-oriented approach (deeper article on it to come soon)

const baseBoolean = {
  setThen: function(then) { return { ...this, then }; },
  setOtherwise: function(otherwise) { return { ...this, otherwise }; },
};

const objectOrientedTrue = {
  ...baseBoolean,
  evaluate: function() { return this.then; },
};

const objectOrientedFalse = {
  ...baseBoolean,
  evaluate: function() { return this.otherwise; },
};

const objectOrientedNumber = {
  value: 0,
  isaMultipleCache: [objectOrientedFalse],
  setValue: function(n) { return { ...this, value: n, isaMultipleCache: [objectOrientedTrue, ...Array(n).fill(objectOrientedFalse)] }; },
  isaMultipleOf: function(dividend) { return this.isaMultipleCache[dividend.value % this.value]; }
};

const objectOrientedFizzBuzz = {
  for: function(n) {
    const number = objectOrientedNumber.setValue(n);
    return this.three
               .isaMultipleOf(number)
               .setThen(
                 this.five
                     .isaMultipleOf(number)
                     .setThen("FizzBuzz")
                     .setOtherwise("Fizz")
                     .evaluate()
               )
               .setOtherwise(
                 this.five
                     .isaMultipleOf(number)
                     .setThen("Buzz")
                     .setOtherwise(number.value)
                     .evaluate()
               )
               .evaluate();
  },
  three: objectOrientedNumber.setValue(3),
  five: objectOrientedNumber.setValue(5),
};

Similarly to the functional approach; the main part of this solution is defining "true" and "false" as objects. But now instead of parameters, the objects have the same interface and return one or the other of the attributes set on the object.

Collapse
 
kallmanation profile image
Nathan Kallman • Edited

As promised, here is my functional approach to solving this (deeper article on it to come soon)

const functionalTrue = (onTrue, onFalse) => onTrue;
const functionalFalse = (onTrue, onFalse) => onFalse;
const isDivisible = (dividend, divisor) => [functionalTrue, ...Array(divisor).fill(functionalFalse)][dividend % divisor];

const functionalFizzBuzz = (n) => {
  const divisible_by_three = isDivisible(n, 3);
  const divisible_by_five = isDivisible(n, 5);
  return divisible_by_three(divisible_by_five("FizzBuzz", "Fizz"), divisible_by_five("Buzz", n));
};

Similar to Heiker's solution above; the main part of this solution is defining "true" and "false" as functions taking the same two parameters but returning one or the other.

Collapse
 
jpantunes profile image
JP Antunes

Still not perfect, but this one comes with a special thanks to Mr. Kevlin Henney

const fizzBuzz = n => {
    const isFizzBuzz = n => ( {false: '', true: 'Fizz'}[n % 3 == 0] 
                            + {false: '', true: 'Buzz'}[n % 5 == 0] 
                            || n.toString() );
    let x = 1;
    return [...Array(n)].map(_ => isFizzBuzz(x++)).toString();                             
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kallmanation profile image
Nathan Kallman

Nice! I like how it uses false and true as keys on an object to select the resulting string.

If you can get rid of the || usage, then this will meet the hard mode requirements...

Collapse
 
jpantunes profile image
JP Antunes • Edited

Well Mr. Henney has a great answer:

const fizzBuzz = n => {
  const test = (d, s, x) => n % d == 0 ? _ => s + x('') : x;
  const fizz = x => test(3, 'Fizz', x);
  const buzz = x => test(5, 'Buzz', x);

  return fizz(buzz(x => x))(n.toString());
}

edit: but it still has a conditional...

 
kallmanation profile image
Nathan Kallman

Excellent! I think you've checked off all the boxes. Thanks for submitting!

Collapse
 
kallmanation profile image
Nathan Kallman

I think your .get is a secret conditional. (It will return the value at the given key or the default IF the value is undefined)

If you can show how to implement .get without an if then I think this is a great answer!

 
avaq profile image
Aldwin Vlasblom

You are referring to the following clause:

Do this without "secret" conditionals like || and && (in loosely typed languages like JavaScript)

My understanding is that this applies to the usage of such operators as conditionals when they are applied to non-boolean types. For example:

const fizz = n % 3 === 0 && 'Fizz' || String(n)

In my code, it is used strictly on Boolean values, which I don't think was against the rules.

Thread Thread
 
kallmanation profile image
Nathan Kallman

It uses it in a strictly boolean sense, which I'll allow. What isn't allowed is the loose/early-return way JS can use &&; a contrived example that would not pass hard mode:

const fizzbuzz = n => (n % 3 && (n % 5 && n || "Buzz")) || (n % 5 && "Fizz" || "FizzBuzz")

(an easy litmus test: does changing the order of the && expression change the result?)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.