PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 23, 2022

[FIXED] How to Interface for a module in javascript

 August 23, 2022     indexing, interface, javascript, module, weekday     No comments   

Issue

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,


Solution

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

  • Template/string literals


Answered By - Andy
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing