aboutsummaryrefslogtreecommitdiff
path: root/part1/anecdotes/src/App.js
blob: 3513cce6bdce0ef53647f71ac6af0627bf317c47 (plain)
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
import { useState } from 'react'

const Button = (props) => {
  return (
    <button onClick={props.onclick}>
      {props.text}
    </button>
  )
}

const App = () => {
  const anecdotes = [
      'If it hurts, do it more often.',
        'Adding manpower to a late software project makes it later!',
        'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
        'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
        'Premature optimization is the root of all evil.',
        'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.',
        'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients.',
          'The only way to go fast, is to go well.'
        
  ]

  const [selected, setSelected] = useState(0)
  const [votes, setVotes] = useState(Array(anecdotes.length).fill(0))
  const [most, setMost] = useState(0)
  

  const getRandomInt = (min, max) => {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min) + min)
  }

  const updateVotes = (selected) => {
    const copy = [...votes]
    copy[selected] += 1
    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))
        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>
  )
}

export default App