xonecas.io
2495
Xg

xonecas.github.com / files

xonecas.github.com / _posts / 2013-02-25-random-title-generator.markdown

1.7 KB
1---
2layout: post
3title: Random Titles
4---
5
6Titles are hard, giving something a name demands thinking about it and making a decision. Unless of course you know some javascript. And... I do. So I can't come up with a title, I'll let the code choose a random(ish) one for us.
7
8This is done with an array of nouns, an array of adjectives and a prefix to the title. The basic idea is to randomly concatenate those terms together. Since the prefix would become repetitive, I've set it to only show up 50% of the times.
9
10Here is the code wrote.
11
12{% highlight javascript %}
13    // for convenience, return a number within the range. Pass the noFloor for a float.
14    function rrange(min, max, noFloor) {
15        var result = Math.random() * (max - min) + min;
16        return noFloor ? result : Math.floor(result);
17    }
18    // generate the title.
19    function randomTitle() {
20        // some nouns and adjectives...
21        var nouns = [ 'Functions', 'Loops', 'Bugs', 'Monkeys', 'Duck', 'String', 'Integers' ],
22            adjs = [ 'Flying', 'Sleeping', 'Typing', 'Parsing', 'Lost', 'Delicious', 'Forgotten' ],
23            // random ints
24            x = rrange(1, nouns.length) - 1,
25            y = rrange(1, adjs.length) - 1,
26            // coin flip for the prefix
27            prefix = Math.random() > 0.5 ? 'The ' : '',
28            // concat it all
29            title = prefix + adjs[y] + ' ' + nouns[x];
30        // set the title
31        $('#random-title').text(title);
32    }
33    $(function () { randomTitle() })
34{% endhighlight %}
35
36There is more that can be done, like adding more nouns and adjectives and different title constructs. If you decide to extend this, or have done something like it, please share your nouns and adjectives.