A clean, testable implementation of the classic FizzBuzz problem — built in TypeScript using a modular architecture.
This application takes a range of numbers (min to max) and applies FizzBuzz rules:
- Numbers divisible by 3 → "Fizz"
- Numbers divisible by 5 → "Buzz"
- Numbers divisible by both 3 and 5 → "FizzBuzz"
- Other numbers → the number itself
- Extensible: Easy to add new rules by implementing the
FizzBuzzStrategyinterface - Priority System: Rules are sorted by priority to ensure correct evaluation order
- Input Validation: Validates user input for numbers and ranges
- Type-Safe: Full TypeScript implementation with proper typing
- Testable: Clean code makes unit testing straightforward
- Error Handling: Comprehensive error handling with user-friendly messages
- The InputHandler asks the user for a minimum and maximum number.
- The FizzBuzzApplication validates the input and generates results.
- The FizzBuzzFormatter applies a set of rules:
FizzRule: multiples of 3 →"Fizz"BuzzRule: multiples of 5 →"Buzz"FizzBuzzRule: multiples of both 3 and 5 →"FizzBuzz"
- The formatted result is printed in the console.
Clone the repository and install dependencies:
git clone https://github.com/k-angama/fizzbuzz-ts.git
cd fizzbuzz-ts
npm installBuild and execute the CLI app:
npm startYou’ll be prompted to enter a minimum and maximum number.
Example:
Enter minimum number: 1
Enter maximum number: 15
=== ✅ FizzBuzz Result ===
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
=== ✅ End ===
This project uses Jest for unit and integration testing.
Run the test suite:
npm testTypical test coverage includes:
FizzBuzzStrategyrulesFizzBuzzFormatterlogicFizzBuzzApplicationflow and error handling
src/
├── core/
│ ├── application/
│ │ ├── FizzBuzzApplication.ts
│ │ └── InputHandler.ts
│ ├── rules/
│ │ ├── FizzBuzzFormatter.ts
│ │ └── FizzBuzzStrategy.ts
│ └── fizzbuzz.ts
├── main.ts
__tests__/
└── (unit tests)
FizzBuzzStrategy: Interface defining the contract for all rules
priority: Determines evaluation order (higher = first)rule(): Boolean condition for when the rule appliesvalue: String to return when the rule matches
FizzBuzzFormatter: Manages and applies rules
- Sorts rules by priority
- Finds the first matching rule for each number
- Returns formatted output string
FizzBuzzApplication: Application controller
- Handles user input flow
- Validates input
- Returns structured result object
InputHandler: Abstracts user input
- Interface allows for easy mocking in tests
- Implementation uses readline
This project is released under the MIT License.