Back to Freecodecamp

Challenge 60: Space Week Day 6: Moon Phase

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68c497f3aaefc9fd9f1b0e24.md

latest1.8 KB
Original Source

--description--

For day six of Space Week, you will be given a date in the format "YYYY-MM-DD" and need to determine the phase of the moon for that day using the following rules:

Use a simplified lunar cycle of 28 days, divided into four equal phases:

  • "New": days 1 - 7
  • "Waxing": days 8 - 14
  • "Full": days 15 - 21
  • "Waning": days 22 - 28

After day 28, the cycle repeats with day 1, a new moon.

  • Use "2000-01-06" as a reference new moon (day 1 of the cycle) to determine the phase of the given day.
  • You will not be given any dates before the reference date.
  • Return the correct phase as a string.

Note: Day 1 represents the day of the new moon, meaning 0 days have passed since the last new moon.

--hints--

moonPhase("2000-01-12") should return "New".

js
assert.equal(moonPhase("2000-01-12"), "New");

moonPhase("2000-01-13") should return "Waxing".

js
assert.equal(moonPhase("2000-01-13"), "Waxing");

moonPhase("2014-10-15") should return "Full".

js
assert.equal(moonPhase("2014-10-15"), "Full");

moonPhase("2012-10-21") should return "Waning".

js
assert.equal(moonPhase("2012-10-21"), "Waning");

moonPhase("2022-12-14") should return "New".

js
assert.equal(moonPhase("2022-12-14"), "New");

--seed--

--seed-contents--

js
function moonPhase(dateString) {

  return dateString;
}

--solutions--

js
function moonPhase(dateString) {
  const ONE_DAY_IN_MS = 1000 * 60 * 60 * 24;
  const refDate = new Date("2000-01-06");
  const targetDate = new Date(dateString);
  const diffMs = targetDate - refDate;
  const diffDays = diffMs / ONE_DAY_IN_MS;
  const phaseDay = (diffDays % 28 + 1);

  if (phaseDay <= 7) {
    return "New";
  } else if (phaseDay <= 14) {
    return "Waxing";
  } else if (phaseDay <= 21) {
    return "Full"
  } else {
    return "Waning";
  }
}