0 / 0 / 0
Регистрация: 03.05.2019
Сообщений: 9
1

Как сделать последнюю задачу на freecodecamp.org

29.07.2022, 12:32. Показов 491. Ответов 2

Author24 — интернет-сервис помощи студентам
Всем привет. В общем пытаюсь получить сертификат по front-end на freecodecamp, долго пытаюсь выполнить последнюю практическую задачу на react.js.

HTML5
1
<div id="root"></div>
CSS
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#root{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100vh;
  background-color: #569;
  color: #fff;
}
 
.clock{
  border: 2px solid silver;
  padding: 40px;
}
 
.clock__header{
  display: flex;
  justify-content: center;
  
  & > * {
    // border: 1px solid #000;
    padding: 0 20px;
  }
}
 
.break-control, .session-control{
  display: flex;
  justify-content: center;
  align-items: center;
}
 
.break-length, .session-length{
  margin: 0 20px;
  font-size: 23px;
}
 
.break-down, .session-down, .break-up, .session-up{
  position: realtive;
  cursor: pointer;
  background-color: transparent;
  border: none;
  width: 25px;
  height: 15px;
  padding: 5px;
  
  &::before{
    content: '';
    display: block;
    position: absolute;
    width: 15px;
    height: 4px;
    background-color: #fff;
    transform: translate(-5px) rotate(45deg);
  }
  
  &::after{
    content: '';
    display: block;
    position: absolute;
    width: 15px;
    height: 4px;
    background-color: #fff;
    transform: translate(5px) rotate(-45deg);
    
  }
  
  &:hover{
    
    &::before{
      background-color: #444;
    }
    &::after{
      background-color: #444;
    }
  }
}
 
.break-up, .session-up{
  
  
  &:before{
    transform: translate(-5px) rotate(-45deg);
  }
  
  &:after{
    transform: translate(5px) rotate(45deg);
    
  }
}
 
.timer{
  margin-top: 40px;
  text-align: center;
  background-color: #79a;
  padding: 40px 0;
  border-radius: 10px;
  
  #timer-label{
    font-size: 1.8em;
    margin-block-end: 0em;
    margin-block-start: 0em;
  }
  
  #time-left{
    font-size: 2.5em;
  }
}
 
.controls{
  display: flex;
  justify-content: space-around;
  margin: 30px auto 0;
  max-width: 100px;
  
  & div{
    font-size: 20px;
    cursor: pointer;
    
    &:hover{
      color: #444;
    }
  }
}
Javascript
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import accurateInterval from "https://cdn.skypack.dev/accurate-interval@1.0.9";
 
const decrement_timer = 'DECREMENT_TIMER';
const break_increment = 'BREAK_INCREMENT';
const break_decrement = 'BREAK_DECREMENT';
const session_increment = 'SESSION_INCREMENT';
const session_decrement = 'SESSION_DECREMENT';
const change_timer = 'CHANGE_TIMER';
const change_mode = 'CHANGE_MODE';
const change_timerID = 'CHANGE_TIMER_ID';
const change_active = 'CHANGE_ACTIVE';
const reset_timer = 'RESET_TIMER'; 
 
const reduser = (state, action) => {
  switch(action.type){
    case decrement_timer:
      return {...state, timer: state.timer - 1}
    case break_increment:
      return {...state, breakLength: state.breakLength + 1}
    case break_decrement:
      return {...state, breakLength: state.breakLength - 1}
    case session_increment:
      return {...state, sessionLength: state.sessionLength + 1}
    case session_decrement:
      return {...state, sessionLength: state.sessionLength - 1}
    case change_timer:
      return {...state, timer: action.payload}
    case change_mode:
      return {...state, timerMode: action.payload}
    case change_timerID:
      return {...state, timerID: action.payload}
    case change_active:
      return {...state, activeTimer: action.payload}
    case reset_timer:
      return {
        breakLength: 5,
        sessionLength: 25,
        timer: 1500,
        activeTimer: false,
        timerMode: 'Session',
        timerID: ''
      }
    default:
      return state
  }
}
 
const default_state = {
  breakLength: 5,
  sessionLength: 25,
  timer: 1500,
  activeTimer: false,
  timerMode: 'Session',
  timerID: ''
}
 
const BreakLength = ({breakLength, breakUp, breakDown}) => {
  
  return (
    <div className="break__body">
      <h2 id="break-label">Break Length</h2>
      <div className="break-control">
        <button onClick={() => breakDown()} id="break-decrement" className="break-down" ></button>
        <div className="break-length" id="break-length">{breakLength}</div>
        <button onClick={() => breakUp()} className="break-up" id="break-increment"></button>
      </div>
    </div>
  );
}
 
const SessionLength = ({sessionLength, sessionUp, sessionDown}) => {
  
  return (
    <div className="session__body">
      <h2 id="session-label">Session Length</h2>
      <div className="session-control">
        <button onClick={() => sessionDown()} className="session-down" id="session-decrement"></button>
        <div className="session-length" id="session-length">{sessionLength}</div>
        <button onClick={() => sessionUp()} className="session-up" id="session-increment"></button>
      </div>
    </div>
  );
}
 
 
const Clock = () => {
  
  // const [breakLength, setBreakLength] = React.useState(5);
  // const [sessionLength, setSessionLength] = React.useState(25);
  // const [timer, setTimer] = React.useState(1500);
  // const [activeTimer, setActiveTimer] = React.useState(false);
  // const [clockMode, setclockMode] = React.useState('Session');
  // const [timerID, setTimerID] = React.useState('');
  
  const [state, dispatch] = React.useReducer(reduser, default_state)
  
  const audio = React.useRef(null);
  
  
  
  const breakUp = () => {
    if(!state.activeTimer && state.breakLength < 60){
      dispatch({type: break_increment});
      if(state.timerMode === 'Break'){
        dispatch({type: change_timer, payload: (state.breakLength + 1) * 60})
      }
    }
  }
  
  const breakDown = () => {
    if(!state.activeTimer && state.breakLength > 1){
      dispatch({type: break_decrement});
      if(state.timerMode === 'Break'){
        dispatch({type: change_timer, payload: (state.breakLength - 1) * 60})
      }
    }
  }
  
  const sessionUp = () => {
    if(!state.activeTimer && state.sessionLength < 60){
      dispatch({type: session_increment});
      if(state.timerMode === 'Session'){
        dispatch({type: change_timer, payload: (state.sessionLength + 1) * 60})
      }
    }
    
  }
  
  const sessionDown = () => {
    if(!state.activeTimer && state.sessionLength > 1){
      dispatch({type: session_decrement});
      if(state.timerMode === 'Session'){
        dispatch({type: change_timer, payload: (state.sessionLength - 1) * 60})
      }
    }
  }
  
  function lengthControl(stateToChange, sign, currentLength, mode){
    if (state.activeTimer) {
      return;
    }
    if (state.timerMode === mode) {
      if (sign === '-' && currentLength <= 1) {
       stateToChange;
      } else if (sign === '+' && currentLength >= 60) {
        stateToChange;
      }
    } else if (sign === '-' && currentLength >= 1) {
        stateToChange;
        // setTimer(currentLength * 60 - 60);
        dispatch({type: change_timer, payload: currentLength * 60 - 60});
    } else if (sign === '+' && currentLength <= 60) {
        stateToChange;
        // setTimer(currentLength * 60 + 60);
        dispatch({type: change_timer, payload: currentLength * 60 + 60});
    }
  }
  
  const decrementTimer = () => {
    dispatch({type: decrement_timer});
  }
  
  const swicthTimer = (time, mode) => {
    // setTimer(time);
    dispatch({type: change_timer, payload: time})
    dispatch({type: change_mode, payload: mode})
  }
  
  const startTimer = () => {
      const ID = accurateInterval(() => {
        decrementTimer();
      }, 1000);
      dispatch({type: change_timerID, payload: ID})
  } 
  
 const timerControl = () => {
    if(!state.activeTimer){
      startTimer();
      dispatch({type: change_active, payload: true})
    } else{
      dispatch({type: change_active, payload: false})
      if(state.timerID){
        state.timerID.clear();
      }
    }
}
 
 
 
 const formatTime = (time) => {
    let minutes = Math.floor(time / 60);
    let seconds = time - minutes * 60;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    return minutes + ':' + seconds;
  }
  
  const reset = () => {
    
    // setSessionLength(25);
    // setBreakLength(5);
    // setActiveTimer(false);
    // setclockMode('Session');
    // setTimer(1500);
    // setTimerID('');
    // if(timerID){
    //   timerID.clear();
    // }
    if(state.timerID){
      state.timerID.clear();
    }
    dispatch({type: reset_timer})
    
    audio.current.pause();
    audio.current.currentTime = 0;
  }
  
  
  // React.useEffect(() => {
  //   dispatch({type: change_timer, payload: state.timer / 60})
  // }, [state.sessionLength])
  
  React.useEffect(() => {
      if(state.activeTimer){
        console.log(state.timer);
        if(state.timer < 0){
        if(state.timerID){
          state.timerID.clear();
        }
        if(state.timerMode === 'Session'){
          startTimer();
          swicthTimer(state.breakLength * 60, 'Break')
        } else{
          startTimer();
          swicthTimer(state.sessionLength * 60, 'Session')
        }
      }
    }
  }, [state.timer])
  
  // React.useEffect(() => {
  //   if(!state.activeTimer){
  //     dispatch({type: change_timer, payload: state.timer});
  //   }
  // }, [state.sessionLength])
  
  React.useEffect(() => {
    if(state.activeTimer){
      if(state.timer == 0){
        audio.current.play();
      }
    }
  }, [state.timer, state.activeTimer])
  
  return(
    <>
    <h1>25 + 5 Clock</h1>
      <div className="clock">
        <div className="clock__header">
          <BreakLength breakLength={state.breakLength} breakUp={breakUp} breakDown={breakDown}   />
          <SessionLength sessionLength={state.sessionLength} sessionUp={sessionUp} sessionDown={sessionDown} />
        </div>
        <div className="timer">
          <h2 id="timer-label">{state.timerMode}</h2>
          <div id="time-left">{formatTime(state.timer)}</div>
          <div className="controls">
            <button onClick={() => timerControl()} id="start_stop">
              {state.activeTimer ? <i className="fa fa-pause"></i>
              : <i className="fa fa-play"></i>}
            </button>
            <button id="reset" onClick={() => reset()}>
              <i className="fa fa-rotate"></i>
            </button>
          </div>
          <audio id="beep" preload="auto" ref={audio} src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/audio/BeepSound.wav"/>
        </div>
      </div>
    </>
  )
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
 
root.render(<Clock/>);
Вот ссылка на песочницу: http://codepen.io/redax7355/pen/LYQKRgB
Ни как не получается пройти тесты, уже по разному пробовал, и с простыми state`ами тоже.
Подскажите что может быть не так и ка можно исправить, заранее спасибо))
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
29.07.2022, 12:32
Ответы с готовыми решениями:

Почему не засчитывает задачу на stepic.org
Напишите программу, которая по заданным двум натуральным числам (каждое не более 10000) --...

Как сделать последнюю активность?
Здравствуйте, есть бд в которой много таблиц назовем их comment,new и т.д. в каждой есть 2 нужных...

Помогите решить последнюю задачу, на двумерный массив
http://img5.imageshost.ru/imgs/ef048fb2ebaa250400d62868648dad75/0ef96cef47a10866152121bab809caa2.jpg...

НАрод, пожалуста, с этого сайта задачу, очень надо сделать задачу
http://www.delphiplus.org/praktikum-po-delphi/prakticheskaya-rabota-34-igra.html

Для линейного программирования составить двойственную задачу. Составленную задачу сделать графическим способом
Доброго времени, народ! Пока болел, пришлось пропустить пару занятий и тут я в в ступоре. Помогите...

2
230 / 170 / 51
Регистрация: 12.03.2021
Сообщений: 969
01.08.2022, 15:18 2
Цитата Сообщение от ReDaX7355 Посмотреть сообщение
Подскажите что может быть не так и ка можно исправить
для начала неплохо было бы описать задачу. если у вас задача, скажем, отразить на карте точки каких-нибудь барбершопов для грудных младенцев - у вас тут всё не верно, исправить можно переписав всё.
0
0 / 0 / 0
Регистрация: 03.05.2019
Сообщений: 9
06.08.2022, 18:25  [ТС] 3
Splaisto, вот ссылка на задачу: https://www.freecodecamp.org/l... 5--5-clock
0
06.08.2022, 18:25
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
06.08.2022, 18:25
Помогаю со студенческими работами здесь

Как в подчинённой форме сделать текущей последнюю запись
Помогите, кто сможет. :-) У меня есть основная форма и подчинённая. В основной форме есть кнопка,...

Как сделать видимой последнюю добавленную строку в datagrid
Уважаемые Гуру! После добавления строки в viewModel последняя добавленная строка не видима в...

Как сделать 5 задачу на C++

как сделать задачу
Сформировать массив A из N элементов случайным образом и целое число М (вводится с клавиатуры или...

Как сделать задачу?
Помогите сделать задачу: Дан двумерный массив целых чисел. а) В каждой его строке заменить любой...

Как сделать задачу
Даётся длина области и количество точек. Найт колчество все х возможные вариантов замощеня, притом...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru