Help for doing Function testing

Trying to finish some testing for Functions in the link as below. Not sure what is the difference between Test Function 1 and Test Function 3.

My codes as below seem more meet the requirement for Test Function 3. Not sure what I should do for Test Function 1. Could somebody help? Thank you.

 <body>
    <section class="preview">

    </section>

  <script>

    let names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada']
    let para = document.createElement('p');
   
    let random=names[Math.floor(Math.random()*names.length)];
    para.textContent=random;

    const section = document.querySelector('section');
    section.appendChild(para);

  </script>
</body>

Hi @Laura! Your code is certainly serving the purpose described in Functions 1, but the idea is that you create a function that will select a random name form the array and then print it to the paragraph.

The difference in Functions 3 is that there we are expecting you to refactor the function from Functions 1 into :

  1. A generic random() function that takes as arguments two bounds, and returns a number between those two bounds.
  2. A chooseName() function that takes as an argument the array to choose from, uses the random() function to choose the name, and returns it.

We then want you to print that random name to the paragraph.

2 Likes

Hi @chrisdavidmills, I have done the modification as below. Could you help to check if my code is correct for Function 1 test and Function 3 test? Thank you.

For Function 1:

function chooseName(){
return names[Math.floor(Math.random()*names.length)]
    };
para.textContent=chooseName();

For Function 3:

function random(min, max){
   min=Math.ceil(min);
   max=Math.floor(max);
   return Math.floor(Math.random()*(max-min+1))+min;
   };

function chooseName() { 
   return names[random (0, 7)]
   };
   
para.textContent=chooseName()
1 Like

hi @Laura!

Some great work here. The first one is perfect.

The second one works fine, although Iā€™d update the chooseName function to the following, so that it will work with any array of names, not just this particular one:

function chooseName(array) { 
  return array[random (0, array.length -1)]
};
   
para.textContent = chooseName(names)
3 Likes

Also, you should explicitly declare the min and max variables inside the random() function, and call them something different to the parameters, to avoid confusion and possible weird behavior:

function random(min, max){
    let minRounded = Math.ceil(min);
    let maxRounded = Math.floor(max);
    return Math.floor(Math.random()*(maxRounded-minRounded+1))+minRounded;
 };
3 Likes

Hi @chrisdavidmills , your code is fantastic. Thank you so much for your help.

@Laura You are very welcome; glad to help!

1 Like