Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created August 15, 2018 17:42
Show Gist options
  • Save karol-majewski/6bad10275bc561d57a57c42041bc819b to your computer and use it in GitHub Desktop.
Save karol-majewski/6bad10275bc561d57a57c42041bc819b to your computer and use it in GitHub Desktop.
enum PokemonType {
Water,
Rock,
Fire,
Air,
Electric,
Poison
}
class Pokemon {
private name?: string;
private color?: string;
private age?: number;
private type?: PokemonType;
private level?: number;
constructor(builder: Pokemon.Builder) {
this.name = builder.name;
this.color = builder.color;
this.age = builder.age;
this.type = builder.type;
this.level = builder.level;
}
}
namespace Pokemon {
/**
* To do: merge namespace with Pokemon.
* To do: spread arguments in constructor.
* To do: optionality.
*/
export class Builder {
public name?: string;
public color?: string;
public age?: number;
public type?: PokemonType;
public level?: number;
public withName(name: string) {
this.name = name;
return this;
}
public withColor(color: string) {
this.color = color;
return this;
}
public withAge(age: number) {
this.age = age;
return this;
}
public hasType(type: PokemonType) {
this.type = type;
return this;
}
public onLevel(level: number) {
this.level = level;
return this;
}
public build() {
return new Pokemon(this);
}
}
}
const pikachu: Pokemon = new Pokemon.Builder()
.withName('Bob')
.withColor('yellow')
.withAge(13)
.hasType(PokemonType.Electric)
.onLevel(15)
.build();
@karol-majewski
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment