Creating our own lorem ipsum generator in JavaScript

Generating content from various random words can be very useful for any kind of test. That’s why today we will create a function that will do this.

Of course, you can use some library, but since creating such a generation is not too difficult and does not take many lines of code, it would be nice to write it yourself.

To generate content, we need three functions and the source of the words themselves:

  1. A function that returns a random number.

  2. A function that gives us a random word.

  3. A function that makes a complete string out of words.

  4. Source of words, specified as an array of strings (can be taken from my Github Gist).


1. Random number generation

Since we want to get a random word from our array, we need to generate a random index. With this in mind, you should be aware of the minimum and maximum value of the array index.

Math.random();
// Returns 0.534098468876492

Using the function Math.random() we get a fractional number from 0 to 1 (not including 1). When we multiply it by, for example, 10, we get a number from 0 to 10 (also not including the upper bound). But in our case, we want to get a number from 0 to 10, including the upper bound.

Math.random() * (10 - 0) + 0;
// Returns 8.448742196214798

But now we still get a fractional number. We must use Math.roundto make it whole.

Math.round(Math.random() * (10 - 0) + 0)
// Returns 6 or 5 or 9 or 10

Thanks to these calculations, we get an integer from 0 to 10, including both boundaries. You can also test this code.

let number = 0;
let steps = 0;
while(number != 10) {
    number = Math.round(Math.random() * (10 - 0) + 0);
    steps = steps + 1;
    console.log('steps', steps)
}

Here you loop until the number is 10. By keeping track of the number of iterations, you can tell how many iterations took. If you run this code multiple times, you will find that the number of iterations through the loop will be different each time.

function randomNumber(min, max) {
    return Math.round(Math.random() * (max - min) + min);
}

This is the final function for getting a random number in a range. Let’s go ahead and make a function to get a random word from an array.


2. Getting a random word

I found a good collection of words to use. You can also find her on Github Gist. In this article, I will use only a part.

const word = [
    "Got",
    "ability",
    "shop",
    "recall",
    "fruit",
    "easy",
    "dirty",
    "giant",
    "shaking",
    "ground",
    "weather",
    "lesson",
    "almost",
    "square",
    "forward",
    "bend",
    "cold",
    "broken",
    "distant",
    "adjective."
]

We will use randomNumber the function we made in the previous step. To get a random number, we need to set the range as follows.

const word = words[randomNumber(0, words.length - 1)];

The lower bound is 0 because array indexes start at 0. The upper bound is easily computed aswords.length - 1 . We set it this way because in our case there are 20 words in the array, so words.length will return 20. But for the previously mentioned reason (indices in an array start at 0), subtract 1 to get the index of the last element.

function getRandomWord() {
    return words[randomNumber(0, words.length - 1)];
}

So we have a second function that returns a random word.


3. Getting a string with random words

Now we want to get some words and make a string out of them. The best solution would be to create an array of 10 elements.

[...Array(10)]
// Returns [undefined, undefined, ....] with 10 items

Using .map method, we can iterate over the array and generate a random word for each element.

[...Array(10)].map(() => getRandomWord())
// Returns ["hand", "close", "ship", "possibly", "metal", "myself", "everybody", "serious", "adult", "favorite"]

Right now we just have an array of random words, but to make it a string we have to separate the elements with a space. This can be done using the method .join('').

[...Array(10)].map(() => getRandomWord()).join('')

We also want to add readability to our line, namely to capitalize the first word. Let’s update the function getRandomWord .

function getRandomWord(firstLetterToUppercase = false) {
    const word = words[randomNumber(0, words.length - 1)];
    return firstLetterToUppercase ? word.charAt(0).toUpperCase() + word.slice(1) : word;
}

Now let’s create a function generateWords . Now in getRandomWord(i === 0) we will pass a comparison of the index with 0 to make the first word (whose index is exactly 0) capitalized.

function generateWords(length = 10) {
    return [...Array(length)].map((_, i) => getRandomWord(i === 0)).join(' ').trim() + '.';
}

4. Completion

We’ve written all the functions so we can look at all the code.

const word = [
    "Got",
    "ability",
    "shop",
    "recall",
    "fruit",
    "easy",
    "dirty",
    "giant",
    "shaking",
    "ground",
    "weather",
    "lesson",
    "almost",
    "square",
    "forward",
    "bend",
    "cold",
    "broken",
    "distant",
    "adjective."
]
function getRandomWord(firstLetterToUppercase = false) {
    const word = words[randomNumber(0, words.length - 1)];
    return firstLetterToUppercase ? word.charAt(0).toUpperCase() + word.slice(1) : word;
}
function generateWords(length = 10) {
    return [...Array(length)].map((_, i) => getRandomWord(i === 0)).join(' ').trim() + '.';
}
function randomNumber(min, max) {
    return Math.round(Math.random() * (max - min) + min);
}

You can test it on runkit.

Thanks for attention.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *