aboutsummaryrefslogtreecommitdiff
path: root/part1
diff options
context:
space:
mode:
authorIbrahim Mkusa <ibrahimmkusa@gmail.com>2023-04-26 22:53:54 -0400
committerIbrahim Mkusa <ibrahimmkusa@gmail.com>2023-04-26 22:53:54 -0400
commit21414b49c86ca8ba6bbc36d09dcdc282cc1ae943 (patch)
tree0d4a2b0d71be81a5e14283b1167b22b473e6c39a /part1
parent7a85d56e787f5e90c4c5e08e1ef0d4a7c50d64a7 (diff)
ex 1.14 displays anecdote with most votes
Diffstat (limited to 'part1')
-rw-r--r--part1/anecdotes/src/App.js25
1 files changed, 24 insertions, 1 deletions
diff --git a/part1/anecdotes/src/App.js b/part1/anecdotes/src/App.js
index 8bc3b2b..3513cce 100644
--- a/part1/anecdotes/src/App.js
+++ b/part1/anecdotes/src/App.js
@@ -23,6 +23,7 @@ const App = () => {
const [selected, setSelected] = useState(0)
const [votes, setVotes] = useState(Array(anecdotes.length).fill(0))
+ const [most, setMost] = useState(0)
const getRandomInt = (min, max) => {
@@ -37,12 +38,34 @@ const App = () => {
return copy
}
+ const findIndexOfMax = () => {
+ let indexMax = 0
+ let maxValue = 0
+ for (let i = 0, len = votes.length; i < len; i++) {
+ if (votes[i] > maxValue) {
+ indexMax = i
+ maxValue = votes[i]
+ }
+
+ }
+
+ return indexMax
+ }
+
return (
<div>
+ <h1>Anecdote of the day</h1>
<p>{anecdotes[selected]}</p>
<p>has {votes[selected]} votes</p>
- <Button onclick={() => {setVotes(updateVotes(selected))}} text="vote" />
+ <Button onclick={() => {
+ setVotes(updateVotes(selected))
+ setMost(findIndexOfMax())
+ }} text="vote" />
<Button onclick={() => setSelected(getRandomInt(0, anecdotes.length))} text="next anecdote" />
+ <h1>Anecdote with most votes</h1>
+ <p>{anecdotes[most]}</p>
+ <p>has {votes[most]} votes</p>
+
</div>
)
}