Skip to content
Snippets Groups Projects
Select Git revision
  • 6609623f3cdcf8d9a4dfb77802429dc33ed146d1
  • main default protected
2 results

App.js

Blame
  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    App.js 2.34 KiB
    import { useState } from 'react'
    
    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 90 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 dianosing patients.',
        'The only way to go fast, is to go well.'
      ]
       
      const newArray = () => {
        var arr = Array(anecdotes.length).fill(0)
        console.log(arr)
        return (arr)
      }
    
      const [selected, setSelected] = useState(0)
      const [votes, setVotes] = useState(Array(anecdotes.length).fill(0))
      const [mostVoted, setMostVoted] = useState(anecdotes[0])
    
      const handleNewClick = () => {
        const x = Math.floor(Math.random() * (anecdotes.length))
        setSelected(x)
        console.log(x)
      }
    
    
      //Handles the increase in the voting array
      //Additionally updates the most voted anecdote
      const handleVote = () => {
        console.log("Updating votes. Votes before update ", votes)
        const copy = [...votes]
        copy[selected] += 1
        setVotes(copy)
        console.log("Votes after update: ", copy)
        console.log(copy)
        setMostVoted(anecdotes[indexOfMax(copy)])
      }
    
      //Finds the index of the largest number in array
      function indexOfMax(arr) {
        if (arr.length === 0) {
            return -1;
        }
    
        var max = arr[0];
        var maxIndex = 0;
    
        for (var i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                maxIndex = i;
                max = arr[i];
            }
        }
    
        return maxIndex;
    }
    
      return (
        <div>
          <h1>Anecdote of the day</h1>
          <p>{anecdotes[selected]}</p>
          <button onClick={handleNewClick}>New anecdote</button>
          <button onClick={handleVote}>Vote</button>
          <h1>Anecdote with the most votes</h1>
          <p>{mostVoted}</p>
        </div>
      )
    }
    
    export default App