exercise 1.14

This commit is contained in:
Anish Lakhwara 2023-05-15 22:22:29 +10:00
parent 030b96edad
commit 69ab203c6c

View file

@ -8,6 +8,21 @@ const Button = ({ handler, text }) => {
) )
} }
const HighScore = ({ highScore, anecdotes, scores }) => {
if (highScore === -1) {
return (
<p>No Highest Scoring Annecdote</p>
)
}
return (
<>
<h2>The Highest Voted Annectdote</h2>
<p>It has {scores[highScore]} votes</p>
<p>{anecdotes[highScore]}</p>
</>
)
}
const App = () => { const App = () => {
const anecdotes = [ const anecdotes = [
'If it hurts, do it more often.', 'If it hurts, do it more often.',
@ -22,6 +37,7 @@ const App = () => {
const [selected, setSelected] = useState(0) const [selected, setSelected] = useState(0)
const [scores, setScores] = useState(Array(anecdotes.length).fill(0)) const [scores, setScores] = useState(Array(anecdotes.length).fill(0))
const [highScore, setHigh] = useState(-1)
const randomText = () => { const randomText = () => {
const value = Math.floor(Math.random() * anecdotes.length) const value = Math.floor(Math.random() * anecdotes.length)
@ -31,6 +47,9 @@ const App = () => {
const VoteUp = () => { const VoteUp = () => {
const copy = [...scores] const copy = [...scores]
copy[selected] += 1 copy[selected] += 1
if (Math.max(...copy) === copy[selected]) {
setHigh(selected)
}
setScores(copy) setScores(copy)
} }
@ -40,6 +59,7 @@ const App = () => {
<Button handler={VoteUp} text="Vote" /> <Button handler={VoteUp} text="Vote" />
<p>{anecdotes[selected]}</p> <p>{anecdotes[selected]}</p>
<p>Votes: {scores[selected]}</p> <p>Votes: {scores[selected]}</p>
<HighScore anecdotes={anecdotes} highScore={highScore} scores={scores} />
</div> </div>
) )
} }