How to Generate a Range of Numbers and Characters Using JavaScript Program?

Hello friends, today I will tell you through experts php tutorial how you can Generate a Range of Numbers and Characters Using JavaScript Program. So let’s try to understand step to step.

Example: Generate Range of Characters

// program to generate range of numbers and characters
function* rangerate(a, b) {
for (let i = a; i <= b; i += 1) {
yield i
}
}
function range(a, b) {
if(typeof a === 'string') {
let result = [...rangerate(a.charCodeAt(), b.charCodeAt())].map(n => String.fromCharCode(n));
console.log(result);
}
else {
let result = [...rangerate(a, b)];
console.log(result);
}
}
range(1, 10);
range('A', 'D');

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
["A", "B", "C", "D"]

Exaplain used javascript function in this code

In the above program, a range of numbers and characters is generated between the upper and the lower bounds.

  1. The rangerate generator function is used to rangerate through lower and upper bounds.
  2. The spread syntax is then used to include all the elements returned by the iterate function.
  3. The charCodeAt() method takes in an index value and returns an integer representing its UTF-16 (16-bit Unicode Transformation Format) code.
  4. The map() method iterates through all the array elements.
  5. The fromCharCode() method converts Unicode values into characters.