Skip to content

Instantly share code, notes, and snippets.

@hekystyle
Last active April 1, 2023 19:14
Show Gist options
  • Select an option

  • Save hekystyle/7b387056072250ca25d336f5c43945fe to your computer and use it in GitHub Desktop.

Select an option

Save hekystyle/7b387056072250ca25d336f5c43945fe to your computer and use it in GitHub Desktop.
OOP Bread + Cutter
class Bread {
constructor(public readonly width: number) {
if (width <= 0) {
throw new Error('width must be positive')
}
}
}
class BreadCutter {
cut(bread: Bread, width: number): Bread[] {
if (width <= 0) {
throw new Error('width must be positive')
}
let remaining = bread.width;
const pieces: Bread[] = [];
while (remaining > 0) {
const pieceWidth = Math.min(remaining, width);
pieces.push(new Bread(pieceWidth));
remaining -= pieceWidth;
}
return pieces;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment