Created
February 2, 2022 12:09
-
-
Save alii/2e47f6a16ee9eba61a4060cc0e955ba5 to your computer and use it in GitHub Desktop.
Overengineering a basic interview question by making the a scalable version of FizzBuzz.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Interceptor { | |
condition(i: number): boolean; | |
execute(i: number): void; | |
} | |
abstract class FizzBuzzUtils { | |
protected isMultipleOf(a: number, multiplier: number) { | |
return a % multiplier === 0; | |
} | |
} | |
class Fizz extends FizzBuzzUtils implements Interceptor { | |
public static new() { | |
return new Fizz(); | |
} | |
private constructor() { | |
super(); | |
} | |
public condition(i: number) { | |
return this.isMultipleOf(i, 3); | |
} | |
public execute() { | |
console.log('Fizz'); | |
} | |
} | |
class Buzz extends FizzBuzzUtils implements Interceptor { | |
public static new() { | |
return new Buzz(); | |
} | |
private constructor() { | |
super(); | |
} | |
public condition(i: number) { | |
return this.isMultipleOf(i, 5); | |
} | |
public execute() { | |
console.log('Buzz'); | |
} | |
} | |
class FizzBuzz extends FizzBuzzUtils implements Interceptor { | |
public static new() { | |
return new FizzBuzz(); | |
} | |
private constructor() { | |
super(); | |
} | |
public condition(i: number) { | |
return this.isMultipleOf(i, 5) && this.isMultipleOf(i, 3); | |
} | |
public execute() { | |
console.log('FizzBuzz'); | |
} | |
} | |
class InterceptorExecutor { | |
public static new(interceptors: Interceptor[]) { | |
return new InterceptorExecutor(interceptors); | |
} | |
private constructor(private readonly interceptors: Interceptor[]) {} | |
public start(start = 1, max = 100) { | |
for (let i = start; i < max; i++) { | |
const matchingInterceptor = this.interceptors.find(interceptor => interceptor.condition(i)); | |
if (!matchingInterceptor) { | |
console.log(i); | |
continue; | |
} | |
matchingInterceptor.execute(i); | |
} | |
} | |
} | |
const executor = InterceptorExecutor.new([ | |
FizzBuzz.new(), | |
Fizz.new(), | |
Buzz.new(), | |
]); | |
executor.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment