DEV Community

loading...

Discussion on: [Challenge] 🐝 FizzBuzz without if/else

Collapse
jpantunes profile image
JP Antunes

There was a similar and equally really good thread about a month ago that had some devilishly clever solutions... highly recommend it!

My contributions below:

//1
const fizzBuzz = n => {
    const mapper = (arr, modulo, txt) => arr
                                    .filter(e => e % modulo == 0)
                                    .forEach(e => arr[arr.indexOf(e)] = txt);
    let x = 1;
    const range = [...Array(n)].map(_ => x++)
    mapper(range, 15, 'FizzBuzz');
    mapper(range, 5, 'Buzz');
    mapper(range, 3, 'Fizz');
    return range.toString();
}

//2
const fizzBuzz = n => {
    let x = 1;
    const range = [...Array(n)].map(_ => x++);
    for (let i = 2; i <= n; i += 3) range[i] = 'Fizz';
    for (let i = 4; i <= n; i += 5) range[i] = 'Buzz';
    for (let i = 14; i <= n; i += 15) range[i] = 'FizzBuzz';
    return range.toString();
}

//3
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();                             
}

//4 ...originally from a Kevlin Henney presentation here: https://youtu.be/FyCYva9DhsI?t=1191
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());
}
Collapse
nombrekeff profile image
Manolo Edge Author

Nice stuff. I will be checking out the thread!

There have been some really clever solutions posted here as well.