loading...

re: Refactoring as a Slow but Necessary Process VIEW POST

FULL DISCUSSION
 

I am happy you were able to solve your problem, I love the feeling of finally figuring out a solution after spending a good chunk of time (and β˜•.. and 🧠) on it.

There is one thing I noticed on your first code snippet: dataKey.

You don't need to keep an additional counter with forEach, the second element on the callback is the index of the array or collection you are iterating (that is true for both, regular arrays and NodeLists). With a pretty small change, you can get rid of that small but real error prone variable.

function renderListItems(list) {
  list.forEach((el, dataKey) => {
    const html = `
      <section class="episode" data-key=${dataKey}>
        <h2 style="text-align: center;">
          ${el.title}
        </h2>
        <div id="buzzsprout-player-${el.id}" class="podcast-player" ></div>
        <span>
          ${el.description} Music credit to <a href="https://soundcloud.com/thisislegang" rel="noopener" target="_blank">Le Gang</a>
        </span>
      </section>`;

    document
      .querySelector("#episode-list")
      .insertAdjacentHTML("beforeend", html);
  });
}

Taking it one step further, instead of calling querySelector for every element of your list, you can cache that value:

function renderListItems(list) {
  const episodeList = document.querySelector("#episode-list");

  list.forEach((el, dataKey) => {
    const html = `
      <section class="episode" data-key=${dataKey}>
        <h2 style="text-align: center;">
          ${el.title}
        </h2>
        <div id="buzzsprout-player-${el.id}" class="podcast-player" ></div>
        <span>
          ${el.description} Music credit to <a href="https://soundcloud.com/thisislegang" rel="noopener" target="_blank">Le Gang</a>
        </span>
      </section>`;

    episodeList.insertAdjacentHTML("beforeend", html);
  });
}

And finally, since this code is doing the same for every element on the list, why not just gather all the strings into a single one and do a single call to insertAdjacentHTML?

function renderListItems(list) {
  const episodeList = document.querySelector("#episode-list");

  const html = list.reduce((aggregator, el, dataKey) => {
    return (
      aggregator +
      `
      <section class="episode" data-key=${dataKey}>
        <h2 style="text-align: center;">
          ${el.title}
        </h2>
        <div id="buzzsprout-player-${el.id}" class="podcast-player" ></div>
        <span>
          ${el.description} Music credit to <a href="https://soundcloud.com/thisislegang" rel="noopener" target="_blank">Le Gang</a>
        </span>
      </section>`
    );
  }, "");

  episodeList.insertAdjacentHTML("beforeend", html);
}
 

This is so great, Erick! Really appreciate you taking the time to share this. Can’t wait to dig in more once I get back to my computer! 😊

Code of Conduct Report abuse