Skip to content

Instantly share code, notes, and snippets.

@etki
Last active October 18, 2020 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etki/a7df370f619c4f0ae0b69f59472c4bc6 to your computer and use it in GitHub Desktop.
Save etki/a7df370f619c4f0ae0b69f59472c4bc6 to your computer and use it in GitHub Desktop.
type Modifier<T> = (value: T) => T;
class Sword {
private modifiers: Modifier<number>[] = [];
private damage;
public constructor(damage: number = 5) {
this.damage = damage;
}
public addModifier(modifier: Modifier<number>): this {
this.modifiers.push(modifier);
return this;
}
public swing(): number {
const randomness = Math.random() * 0.2;
const multiplier = 0.9 + randomness;
let damage = this.damage * multiplier;
for (modifier of this.modifiers) {
damage = modifier(damage);
}
return damage;
}
}
const personalBranding = damage => damage + 1;
const enhancedSteel = damage => damage * 2;
const wearness = damage => damage * 0.9;
const shword = new Sword();
shword.swing(); // ~5
shword
.addModifier(personalBranding)
.addModifier(enhancedSteel)
.addModifier(wearness)
shword.swing(); // 5 & + 1 & * 2 & * 0.9 ~= 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment