DEV Community

Cover image for Number Generator With JS
Walter Nascimento
Walter Nascimento

Posted on

Number Generator With JS

[Clique aqui para ler em português]

Here we have a project that generates random numbers, odd numbers, even numbers and real numbers.

Code

First let’s create the interface, we’ll do something simple, using just HTML.

<h1>Gerador de números</h1>

<form name="form_main">
  <div>
    <label for="number">Quantidade</label>
    <input type="number" id="number" />
  </div>
  <div>
    <label for="type">Tipo</label>
    <input type="radio" name="type" id="odd" value="odd" />
    <label for="odd">Impar</label>
    <input type="radio" name="type" id="even" value="even" />
    <label for="even">Par</label>
    <input type="radio" name="type" id="real" value="real" checked='checked' />
    <label for="real">Reais</label>
  </div>

  <button type="button" name="generate">Gerar</button>

  <div id="output"></div>
</form>
Enter fullscreen mode Exit fullscreen mode

In this code we have an input that will define the amount of number we want to generate, in the type (radio) we have options (odd, even and real) and finally we have a button that calls the function to generate the numbers.

"use strict";

let button = document.form_main.generate;
button.addEventListener('click', generate);

function generate() {
  let output = document.getElementById('output');
  let total = document.form_main.number.value;
  let type = document.form_main.type.value;
  let numbers = [];

  switch (type) {
    case 'odd':
      numbers = generateOdd(total);
      break;
    case 'even':
      numbers = generateEven(total);
      break;
    case 'real':
    default:
      numbers = generateReal(total);
      break;
  }

  output.innerHTML = numbers;
}

function generateOdd(total) {
  let numbers = [];
  let odd = 0;
  for (let index = 0; index < total; index++) {
    while (odd % 2 == 0) { odd++; }
    numbers.push(odd);
    odd++;
  }
  return numbers;
}

function generateEven(total) {
  let numbers = [];
  let even = 0;
  for (let index = 0; index < total; index++) {
    while (even % 2 != 0) { even++; }
    numbers.push(even);
    even++;
  }
  return numbers;
}

function generateReal(total) {
  let numbers = [];
  for (let index = 0; index < total; index++) {
    numbers.push(index);
  }
  return numbers;
}
Enter fullscreen mode Exit fullscreen mode

Here we have the javascript code that does all the magic, in the first line we have the selection of the button that calls the generate function, where the type that must be generated is checked and then its respective function is called.

We have three functions:

  • generateOdd = This function loops over the total amount of numbers that must be generated and in the while statement it is checked if the number is even and finally it returns all the even numbers generated;
  • generateEven = This function loops over the total amount of numbers that must be generated and in the while statement it is checked if the number is odd, finally, all the generated odd numbers are returned;
  • generateReal = This function loops over the total amount of numbers that must be generated, finally all generated numbers are returned;

ready simple like that.

Demo

See below for the complete working project.

Youtube

If you prefer to watch it, see the development on youtube.


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊

Top comments (4)

Collapse
 
ecrelier profile image
ECrelier

Hello Walter, my Google feed randomly suggested me this article this morning.
By you video, I'm assuming that you are Brazilian like me! Don't get me wrong I do not intent to be demeaning, patronizing or anything like that, but your code has a lot of unnecessary and redundant code.
If you don't mind I forked and changed to be more efficient with really neat tricks!
Please have a look and reach me out if you have any questions codepen.io/Crelier/pen/jOLXmop

Collapse
 
oskargrosser profile image
Oskar Grosser

As refreshing as it was to see a switch-block in JS, I do agree that a lookup table is likely a better fit in JS, simply because it is easy to implement and understand. Though I would have the numbers be generated by the lookup functions, instead of just checking whether they are of a certain type.
Also, ECrelier, your function names seem misleading. For example, "real" returns true for every number, but "even" and "odd" return true when a number is not even or odd, respectively. I would pass a pre-increment (++contador) instead of a post-increment.

I did not know that elements with an ID are objects on the global object, awesome!
Now that we are already trying to skip looking through the document, we can wrap the <input>s and the <button> in a <form>. That way, we can access all the named values like so: form.name.value. This even works for radio-groups!

And while we are using a <form> already, we may even use an <output> as well. It is an aria-live region by default, so it is giving live feedback from the result of our <form> to the user. This is good for accessibility reasons!

When using a <form>, we can also make the "total" number-input required. That way, our form-element is only submitted once all required input-fields are filled out validly.
Note: By default, a form-submission is a GET-request to the current URL. To prevent this, use event.preventDefault().

And, ECrelier, to your argument that we should not use a <form>, here is my opinion:

  • The WAI-ARIA specification does explicitely allow the use of client-sided form-evalutations, especially if the user is informed of such.
  • The HTML specification does not specify as to how a submission has to be processed by developers, only how it should be processed by default.
  • And MDN (though only a community-created wiki) states that web forms can be "used on the client-side".

In my opinion, we are filling out a form, and request it to be processed (one may call this "submitting"). This "submission" is just handled client-sided, instead of server-sided.
As I said, this is just my opinion and interpretation of the specifications, and everyone may have their own regarding this topic. I just hope that I changed your mind from "no, never use it like this" to "okay, if you want to, you can do so".

I also did not know that you can just assign an array to .innerHTML, .innerText and .textContent! I would have used Array.join() to transform it to a string before assigning it. But yours is cleaner and easier to read, will definitely use it in the future!

Here is a pen with how I would do it, plus comments to your version:
codepen.io/oskargrosser/pen/mdMaGxo

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

Hi Oskar, thanks for contributing, I really enjoyed the comment, I'll enjoy and improve my code even more, thanks ;)

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

Yes I'm brazilian ;)

I really liked the tips, I'll use them in the next ones, thanks .