2022-03-01

 01 Mar 2022

FizzBuzz

Print integers one through n, but print ‘Fizz’ if an integer is divisible by three, ‘Buzz’ if an integer is divisible by five, and ‘FizzBuzz’ if an integer is divisible by both three and five.

Solution

This is the answer I came up with:

const f = (num: number): any => {
  return (num % 3 === 0) ? 'Fizz' : num
}

const b = (num: number): any => {
  return (num % 5 === 0) ? 'Buzz' : num
}

const fb = (num: number): any => {
  return ( num % 3 === 0 && num % 5 === 0 ) ? 'FizzBuzz' : num
}

const fizzBuzz = (length: number): any => {
  for(let i = 1; i < length + 1; i++) {
    console.log(f(b(fb(i))))
  }
}

fizzBuzz(100)

Since the functionalities for Fizz, Buzz, and FizzBuzz are separate, it makes sense to create individual functions for each condition. I then created the final fizzBuzz function using composition, which I think was an elegant solution.

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZjAvDAFGArgWwFww5gIwFMAnASlwEMwBPJAPhgG8BYAKBhhKKnRLFT4YAUhgBmJImQAGMjAD8MAOQAxAJYAvDUpi587AL7t2oSLAJJBWPVmLkqtBs3aduvflcwiYAVkky5RSUAIXQtHRtMQ2M2U2h4C2Q0azxbUgoYajpERlYOLh4+ARRUr1EJKRkYADJq0u8-SphpGEDldS1Q8N1S6LYTcHi4TQ0ujUsUABsiMABzKAALSLsMrKc8zjgQEimeGDVLAEYAbn2YAB4YabnFmABqGBP9u7u5Dc4YOJBpgDpJkFmKDgKAIQNBajIkLILhgRjYcPYw06YQ0KEO0lk7CAA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated November 7, 2023 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems