Last active
April 1, 2023 19:14
-
-
Save hekystyle/7b387056072250ca25d336f5c43945fe to your computer and use it in GitHub Desktop.
OOP Bread + Cutter
This file contains hidden or 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
| 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