-2

I am just beginner to javascript. I ought to replace blablabla with a code which output the following

There are 7 days in a week.

In programming, the index of Sunday tends to be 0.

Here is the code

const weekday = (function() {
   const names = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];


**blablabla**



})();

var num = 0;

console.log("There are " + weekday.count() + " days in a week.");
console.log("In programming, the index of " + weekday.name(num) + " tends to be " + weekday.number(weekday.name(num)) + ".");

Thanks and Regards,

  • This looks like a homework question. Which is fine but [be aware of the guidelines](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions). I suppose the first question is: do you understand the code that you've posted in your question? – Andy Aug 21 '22 at 13:50
  • Hi Andy, somehow yes! But when I am applying the interface, an error message is poping up saying that I should initialize it first. So, I would like to get your support in this. – Musta_Jaguaari Aug 21 '22 at 14:30

1 Answers1

0

The key to understanding this is realising that the immediately-invoked function (IIF) needs to return an object and assign it to weekday, and that object needs to contain functions (or references to functions) that you can call.

For example: weekday.count() - weekday is an object that has a function assigned as a value to its count key. That object is what is returned from the IIF and assigned to weekday. weekday.count() calls that function.

So the IFF should contain the following functions:

  1. count - returns the length of the names array.
  2. name - returns the element in the names array at the index you supply as an argument.
  3. number - returns the index of the "weekday" string you pass in as an argument.

Then add references to those functions to an object which is returned from the function and assigned to weekday.

const weekday = (function() {
  
  const names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

  function count() {
    return names.length;
  }
  
  function name(n) {
    return names[n];
  }

  function number(str) {
    return names.findIndex(el => el === str);
  }

  return { count, name, number };

})();

const num = 0;

console.log(`There are ${weekday.count()} days in a week.`);

console.log(`In programming the index of ${weekday.name(num)} tends to be ${weekday.number(weekday.name(num))}.`);

Additional documentation

Andy
  • 61,948
  • 13
  • 68
  • 95
  • 1
    Thank you for the explanation. Now I have got the key point of the solution. Frankely, I did not expect this. I was focusing on the return interface. However, the key point of the solution was how to link the 2 functions (number and name) to the declared variable in the beginning. I was busy in the return interface code. – Musta_Jaguaari Aug 21 '22 at 15:35