Skip to content

Commit 0a6e45d

Browse files
committed
refactor: use union and mapped types
1 parent 91635bb commit 0a6e45d

File tree

1 file changed

+24
-36
lines changed

1 file changed

+24
-36
lines changed
Lines changed: 24 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,28 @@
11
import { Component, computed, signal } from '@angular/core';
22

3-
enum Difficulty {
4-
EASY = 'easy',
5-
NORMAL = 'normal',
6-
}
3+
type Difficulty = keyof typeof difficulty;
4+
const difficulty = {
5+
easy: 'easy',
6+
normal: 'normal',
7+
};
78

8-
enum Direction {
9-
LEFT = 'left',
10-
RIGHT = 'right',
11-
}
9+
type Direction = 'left' | 'right';
10+
type DirectionMap = { [key in Direction]: string };
11+
const directions: DirectionMap = {
12+
left: 'left',
13+
right: 'right',
14+
};
1215

1316
@Component({
1417
imports: [],
1518
selector: 'app-root',
1619
template: `
1720
<section>
1821
<div>
19-
<button mat-stroked-button (click)="difficulty.set(Difficulty.EASY)">
22+
<button mat-stroked-button (click)="difficulty.set('easy')">
2023
Easy
2124
</button>
22-
<button mat-stroked-button (click)="difficulty.set(Difficulty.NORMAL)">
25+
<button mat-stroked-button (click)="difficulty.set('normal')">
2326
Normal
2427
</button>
2528
</div>
@@ -28,10 +31,8 @@ enum Direction {
2831
2932
<section>
3033
<div>
31-
<button mat-stroked-button (click)="direction.set(Direction.LEFT)">
32-
Left
33-
</button>
34-
<button mat-stroked-button (click)="direction.set(Direction.RIGHT)">
34+
<button mat-stroked-button (click)="direction.set('left')">Left</button>
35+
<button mat-stroked-button (click)="direction.set('right')">
3536
Right
3637
</button>
3738
</div>
@@ -53,30 +54,17 @@ enum Direction {
5354
`,
5455
})
5556
export class AppComponent {
56-
readonly Difficulty = Difficulty;
57-
readonly difficulty = signal<Difficulty>(Difficulty.EASY);
57+
readonly difficulty = signal<Difficulty>('easy');
5858

59-
readonly Direction = Direction;
6059
readonly direction = signal<Direction | undefined>(undefined);
6160

62-
readonly difficultyLabel = computed<string>(() => {
63-
switch (this.difficulty()) {
64-
case Difficulty.EASY:
65-
return Difficulty.EASY;
66-
case Difficulty.NORMAL:
67-
return Difficulty.NORMAL;
68-
}
69-
});
61+
readonly difficultyLabel = computed<string>(
62+
() => difficulty[this.difficulty()],
63+
);
7064

71-
readonly directionLabel = computed<string>(() => {
72-
const prefix = 'You chose to go';
73-
switch (this.direction()) {
74-
case Direction.LEFT:
75-
return `${prefix} ${Direction.LEFT}`;
76-
case Direction.RIGHT:
77-
return `${prefix} ${Direction.RIGHT}`;
78-
default:
79-
return 'Choose a direction!';
80-
}
81-
});
65+
readonly directionLabel = computed(() =>
66+
this.direction()
67+
? `You chose to go ${directions[this.direction()!]}`
68+
: 'Choose a direction',
69+
);
8270
}

0 commit comments

Comments
 (0)