4
\$\begingroup\$

I'm simply getting the 3 future days from an array of objects based on the current day to display for a weather component.

This is the first time I've attempted using ES6 and it's features so please take this into consideration.

Is there a better way to do this and save the values? Have I overcomplicated the whole thing?

const days = [
  {0: 'Sun'},
  {1: 'Mon'},
  {2: 'Tue'},
  {3: 'Wed'},
  {4: 'Thu'},
  {5: 'Fri'},
  {6: 'Sat'}
];
let currentDay = new Date(Date.now()).getDay();
const offset = currentDay + 1;
const daysLength = days.length;
let counter = 0;
let newDays = [];

for (const [i, day] of days.entries()) {
  // set the index start point.
  let pointer = (i + offset) % daysLength;
  newDays.push(days[pointer][pointer]);
  counter++
  if (counter === 3) { break; }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Yes, you have overcomplicated things. But it's nothing dramatic.

First, you defined a two-dimensional table for getting the name of a day. You can replace this with a one-dimensional array.

const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

With this definition, you can just say dayNames[pointer] instead of your current dayNames[pointer][pointer].

The for loop should be of the form for (let i = 0; i < 3; i++) { }, which is the idiomatic form of saying three times.

const today = (new Date()).getDay();
const nextDays = [];
for (let i = 0; i < 3; i++) {
  nextDays.push(dayNames[(today + 1 + i) % dayNames.length]);
}

This counts i from 0 to 2. At first it may feel a bit easier to let i count from 1 to 3 instead, making the + 1 unnecessary. Amongst experienced programmers, almost all loops start at 0 though, so whenever you start a loop at a nonzero number, you will confuse them a little bit.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.