フロントエンジニアになるための練習問題 押すと色が変わるボタン6

前回の課題の続きです。

課題

今回はクライアントからの依頼ではなく、これまでのコードを少しリファクタリングしてみます。

今のコードはこんな感じです。

        const getRandom = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

        const getClass = (value) => {
          switch (value) {
            case 1: {
              return 'red-active';
            }
            case 2: {
              return 'blue-active';
            }
            case 3: {
              return 'yellow-active';
            }
          }
        };

        let canClick = true;
        const startButtonEl = document.getElementById("start-button");

        startButtonEl.addEventListener("click", () => {
          if(!canClick) return;

          canClick = false;
          startButtonEl.innerText = '処理中...';

          setTimeout(() => {
            canClick = true;
            startButtonEl.innerText = 'ボタン';
          }, 5000);

          if(startButtonEl.classList.contains("red-active") || startButtonEl.classList.contains("blue-active") || startButtonEl.classList.contains("yellow-active")){
            startButtonEl.classList.remove("red-active", "blue-active", "yellow-active");
          }else{
            const value = getRandom(1, 3);
            const applyClass = getClass(value);
            startButtonEl.classList.add(applyClass);
          }
        });

フラグをfalseにしてテキストを「処理中…」にする処理と、

フラグをtrueにしてテキストを「ボタン」にする処理は関数にした方が何をしているかわかりやすくなりそうです。

以下のように、inactiveButtonとactiveButtonという関数にしてみました。

        const getRandom = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

        const getClass = (value) => {
          switch (value) {
            case 1: {
              return 'red-active';
            }
            case 2: {
              return 'blue-active';
            }
            case 3: {
              return 'yellow-active';
            }
          }
        };


        let canClick = true;
        const startButtonEl = document.getElementById("start-button");

        startButtonEl.addEventListener("click", () => {

          const inactiveButton = () => {
            canClick = false;
            startButtonEl.innerText = '処理中...';
          };
          
          const activeButton = () => {
            canClick = true;
            startButtonEl.innerText = 'ボタン';
          };

          if(!canClick) return;

          inactiveButton();

          setTimeout(() => {
            activeButton();
          }, 5000);

          if(startButtonEl.classList.contains("red-active") || startButtonEl.classList.contains("blue-active") || startButtonEl.classList.contains("yellow-active")){
            startButtonEl.classList.remove("red-active", "blue-active", "yellow-active");
          }else{
            const value = getRandom(1, 3);
            const applyClass = getClass(value);
            startButtonEl.classList.add(applyClass);
          }
        });

関数名からなんとなく何をするかわかるので少し理解しやすくなったと思います。