如何通过实现 DRY 原则使这段代码成为可重用的函数?

How can I make this code into a reuseble function by implementing DRY principle?

我正在尝试将我的代码应用到一个带有参数的简单 function 中,并根据 DRY 原则使其可重用。如您所见,我在 addEventListener Function 中使用了完全相同的代码。 这是我想在 addEventListener function :

中重用的代码
 rightBtn.addEventListener("click", () => {
      activeSlide++;
      if (activeSlide > slides.length - 1) {
        activeSlide = 0;
      }
    });

    leftBtn.addEventListener("click", () => {
      activeSlide--;
      if (activeSlide < 0) {
        activeSlide = slides.length - 1;
      }
    });

它们只是看起来相似,但完全不同。

你可以这样做:

const changeSlide = diff => () => {
  activeSlide += diff;
  if (activeSlide < 0) {
    activeSlide = slides.length - 1;
  } else if (activeSlide > slides.length - 1) {
    activeSlide = 0;
  }
  return activeSlide;
};
rightBtn.addEventListener("click", changeSlide(1));
leftBtn.addEventListener("click", changeSlide(-1));

您可以简单地创建一个函数,该函数传入一个值,您可以根据该值递增或递减幻灯片索引。然后您可以更新幻灯片索引,如下面的代码片段所示。

const slides = ["Apple", "Mango", "Banana"];
let currSlide = 0;

const leftBtn = document.querySelector("#leftBtn");
const rightBtn = document.querySelector("#rightBtn");
const content = document.querySelector("#content");

content.innerText = slides[currSlide];

const changeSlide = (delta) => {
  currSlide = (currSlide + delta + slides.length) % slides.length;
  content.innerText = slides[currSlide];
};

leftBtn.addEventListener("click", () => changeSlide(-1));
rightBtn.addEventListener("click", () => changeSlide(1));
<button id="leftBtn">Left</button>
<span id="content"></span>
<button id="rightBtn">Right</button>