Untitled

mail@pastecode.io avatar
unknown
javascript
2 months ago
2.1 kB
1
Indexable
Never
import React, { useState, useRef } from 'react';

const Home = () => {
  const [temperaturos, setTemperaturos] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const averageTemperatureRef = useRef(null);

  const addTemperature = () => {
    if (inputValue !== '') {
      const newTemperaturos = [...temperaturos, parseFloat(inputValue)];
      setTemperaturos(newTemperaturos);
      setInputValue('');
      calculateAverageTemperature(newTemperaturos);
    }
  };

  const clearTemperatures = () => {
    setTemperaturos([]);
    averageTemperatureRef.current = null;
  };

  const calculateAverageTemperature = (newTemperaturos) => {
    const sum = newTemperaturos.reduce((acc, temp) => acc + temp, 0);
    const average = sum / newTemperaturos.length;
    averageTemperatureRef.current = average;
  };
  
  const findMinTemperature = () => {
    return Math.min(...temperaturos);
  };

  const findMaxTemperature = () => {
    return Math.max(...temperaturos);
  };

  const findTemperatureDifference = () => {
    const minTemperature = findMinTemperature();
    const maxTemperature = findMaxTemperature();
    return maxTemperature - minTemperature;
  };

  return (
    <div>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          addTemperature();
        }}
      >
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button type="submit">Pridėti temperatūrą</button>
      </form>

      {temperaturos.length > 0 && (
        <div>
          <p>Temperatūros: {temperaturos.join(', ')}</p>
          <p>Vidutinė temperatūra: {averageTemperatureRef.current}</p>
          <p>Temperatūrų skaičius: {temperaturos.length}</p>
          <p>Žemiausia temperatūra: {findMinTemperature()}</p>
          <p>Aukščiausia temperatūra: {findMaxTemperature()}</p>
          <p>Temperatūrų skirtumas: {findTemperatureDifference()}</p>
          <button onClick={clearTemperatures}>Išvalyti temperatūras</button>
        </div>
      )}
    </div>
  );
};

export default Home;
Leave a Comment