관리 메뉴

샐님은 개발중

8강 반응속도 체크 - reduce 본문

자바스크립트/인프런강의-렛츠기릿 자바스크립트

8강 반응속도 체크 - reduce

샐님 2023. 7. 5. 22:51
728x90
반응형

1. reduce

   const arry = [1, 2, 3, 4];
        // a는 누적값, c는 현재값
        arry.reduce((a, c) => {
            return a + c
        });

 


        //{} :초기값, 배열을 객체리터럴로 바꿀때 사용할수 있다.
        arry.reduce((a, c) => {
            a[c] = c * 10;
            return a;
        }, {});

 

 

2. 전체 코드

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>반응속도</title>
    <style>
        #screen {
            width: 300px;
            height: 200px;
            text-align: center;
            user-select: none;
        }
       
        #screen.waiting {
            background-color: aqua;
        }
       
        #screen.ready {
            background-color: red;
            color: white;
        }
       
        #screen.now {
            background-color: greenyellow;
        }
    </style>
</head>

<body>
    <div id="screen" class="waiting">클릭해서 시작하세요</div>
    <div id="result"></div>
    <script>
        const $screen = document.querySelector("#screen");
        const $result = document.querySelector("#result");


        let starttime;
        let endtime;
        let timeoutId;
        const records = [];
        const screenclick = () => {
            if ($screen.classList.contains("waiting")) {
                //빨간 화면으로 전환함
                $screen.classList.remove("waiting");
                $screen.classList.add("ready")
                $screen.textContent = '초록색이 되면 클릭하세요.';
                //램던 타이머 작동
                timeoutId = setTimeout(() => {
                    $screen.classList.remove("ready");
                    $screen.classList.add("now")
                    $screen.textContent = '클릭하세요!';
                    //시간 재기
                    starttime = new Date();
                }, Math.floor(Math.random() * 1000) + 2000);
                //초록화면 띄우고 시간 잼

            } else if ($screen.classList.contains("ready")) {
                clearTimeout(timeoutId);
                $screen.classList.remove("ready");
                $screen.classList.add("waiting")
                alert("성급했습니다.");

            } else if ($screen.classList.contains("now")) {
                //끝 시간 재기
                //시간 차이 저장하기
                endtime = new Date();
                const current = endtime - starttime;
                records.push(current);
                const average = records.reduce((a, c) => a + c) / records.length;
                $result.textContent = `현재 : ${current}, 평균 : ${average}ms`;
                starttime = null;
                endtime = null;
                $screen.classList.remove('now');
                $screen.classList.add('waiting');
                $screen.textContent = '클릭해서 시작하세요.';

            }
        }

        addEventListener('click', screenclick);
    </script>
</body>

</html>

 

3. 셀프 체크 - 반응 속도중 반응속도가 빠른 상위 5개만보여주기

// sort 로 정렬후 5개만 보여줍니다.
// slice 는 5개를 가져오더라도 값이 1개면 1개만 가져온다.
 
 const topFive = records.sort((a, b) => (a - b)).slice(0, 5);
                topFive.array.forEach((element, index) => {
                    $result.append(
                        document.createElement('br'),
                        `${index+1}위 : ${element}ms`,
                    );
                });
728x90
반응형