-
Notifications
You must be signed in to change notification settings - Fork 0
/
LottoClass.tsx
108 lines (96 loc) · 2.41 KB
/
LottoClass.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import * as React from "react"
import { Component } from "react"
import Ball from "./Ball"
function getWinNumbers() {
console.log("getWinNumbers")
const candidate = Array(45)
.fill(null)
.map((v, i) => i + 1)
const shuffle = []
while (candidate.length > 0) {
shuffle.push(
candidate.splice(Math.floor(Math.random() * candidate.length), 1)[0]
)
}
const bonusNumber = shuffle[shuffle.length - 1]
const winNumbers = shuffle.slice(0, 6).sort((p, c) => p - c)
return [...winNumbers, bonusNumber]
}
interface State {
winNumbers: number[]
winBalls: number[]
bonus: number | null
redo: boolean
}
class LottoClass extends Component<{}, State> {
state: State = {
winNumbers: getWinNumbers(),
winBalls: [],
bonus: null,
redo: false,
}
timeouts: number[] = []
runTimeouts = () => {
console.log("runTimeouts")
const { winNumbers } = this.state
for (let i = 0; i < winNumbers.length - 1; i++) {
this.timeouts[i] = window.setTimeout(() => {
this.setState((preState) => {
return { winBalls: [...preState.winBalls, winNumbers[i]] }
})
}, (i + 1) * 1000)
}
this.timeouts[6] = window.setTimeout(() => {
this.setState({
bonus: winNumbers[6],
redo: true,
})
}, 7000)
}
componentDidMount(): void {
console.log("didMount")
this.runTimeouts()
console.log("로또 숫자 생성")
}
componentDidUpdate(prevProps: {}, prevState: State) {
console.log("didUpdate")
if (this.state.winBalls.length === 0) {
this.runTimeouts()
}
if (prevState.winNumbers !== this.state.winNumbers) {
console.log("로또 숫자를 생성합니다.")
}
}
componentWillUnmount() {
this.timeouts.forEach((v) => {
clearTimeout(v)
})
}
onClickRedo = () => {
console.log("onClickRedo")
this.setState({
winNumbers: getWinNumbers(),
winBalls: [],
bonus: null,
redo: false,
})
this.timeouts = []
}
render() {
const { winBalls, bonus, redo } = this.state
return (
<>
<div>당첨 숫자</div>
<div id="결과창">
{winBalls.map((v) => (
<Ball key={v} number={v} />
))}
</div>
<div>보너스!</div>
{bonus && <Ball number={bonus} />}
{redo && <button onClick={this.onClickRedo}>한 번 더!</button>}
</>
)
}
}
export default LottoClass