logictesttypescript

Tackling FizzBuzz in TypeScript

2 min read
0 views






Hey future me (or whoever stumbles on this), Remember that classic FizzBuzz puzzle? The one that trips up folks in interviews because it's deceptively simple but tests your basics: loops, conditionals, modulo ops.I write code in TypeScript today—why? 'Cause TS is my go-to for front-end stuff lately, and it's fun to see how the typing shakes things up. Plus, practicing cross-lang implementations keeps the brain sharp.

Quick recap: Print numbers from 1 to 100 (or whatever range), but swap in "Fizz" for multiples of 3, "Buzz" for 5, and "FizzBuzz" for both. Easy peasy, but let's make it robust with params, error checks, and TS flair.

The Code Snippet

Here's the function. I tucked it in a module-style export for reusability. Drop this in a fizzbuzz.ts file and you're golden.

fizzbuzz.ts
/** * Comprehensive FizzBuzz Implementation for Coding Tests (TypeScript Edition) *  * Flexible FizzBuzz: Customize range, divisors, and strings. Efficient O(n) loop. * Handles edges like empty ranges or bad inputs. *  * Usage: fizzbuzz({ start: 1, end: 100 }); // Logs to console *  * Example Output (1-15): * 1 * 2 * Fizz * 4 * Buzz * ... up to FizzBuzz at 15 */// Define options interface for that sweet type safetyinterface FizzBuzzOptions {  start?: number;  end?: number;  fizzDivisor?: number;  buzzDivisor?: number;  fizzStr?: string;  buzzStr?: string;}function fizzbuzz(options: FizzBuzzOptions = {}): void {  // Defaults—TS loves these  const {    start = 1,    end = 100,    fizzDivisor = 3,    buzzDivisor = 5,    fizzStr = "Fizz",    buzzStr = "Buzz"  } = options;  // Input validation—throw early, fail fast  if (typeof start !== 'number' || typeof end !== 'number' ||       typeof fizzDivisor !== 'number' || typeof buzzDivisor !== 'number') {    throw new TypeError("Numeric args must be numbers (TS will catch most at compile-time).");  }    if (start > end) {    throw new RangeError("Start must be <= end—can't go backwards in time!");  }    if (fizzDivisor <= 0 || buzzDivisor <= 0) {    throw new RangeError("Divisors gotta be positive integers—no dividing by zero or negatives.");  }    if (typeof fizzStr !== 'string' || typeof buzzStr !== 'string') {    throw new TypeError("Fizz/Buzz strings must be... strings.");  }  // The magic loop—single pass, no extras  for (let i = start; i <= end; i++) {    let output = '';        if (i % fizzDivisor === 0) {      output += fizzStr;    }        if (i % buzzDivisor === 0) {      output += buzzStr;    }        // If no fizz/buzz, just the number    if (!output) {      output = i.toString();    }        console.log(output);  }}// Export for module use—'cause why not?export default fizzbuzz;// Quick test runnerif (require.main === module) {  fizzbuzz(); // Standard 1-100  console.log('\n--- Custom Test (1-20, Foo/Bar) ---');  fizzbuzz({ end: 20, fizzStr: 'Foo', buzzStr: 'Bar' });}

Running It

  • Setup: npm init -y, npm i -D typescript ts-node @types/node. Add "scripts": { "start": "ts-node fizzbuzz.ts" } to package.json.
  • Test: npm start. Watch it spit out the sequence. Tweak params for fun—try fizzbuzz({ start: 0, fizzDivisor: 1 }) (should error on divisor=1? Nah, but multiples of 1 is everything Fizz!).
  • Interview Tip: In a live session, I'd verbalize the logic first: "Loop from start to end, check %3 then %5, concat strings, fallback to num." Then code it clean like this. TS adds polish without overkill.

Random Thoughts

  • Pros of TS Here: Params are typed, so IDE autocompletes like a dream. Catches "str(i)" nonsense before runtime.
  • Cons: Verbose validation.
  • Extensions?: Maybe return an array instead of logging? Or async for big ranges? Future me, you decide.
  • Why Today?: Bingeing old coding vids—FizzBuzz always sparks joy (or mild existential dread).
0
Back to notes