-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathreadable.js
More file actions
87 lines (77 loc) · 2.41 KB
/
readable.js
File metadata and controls
87 lines (77 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const adjectives = require('./words/adjective.json')
const nouns = require('./words/nouns.json')
/**
* Initializes the object.
* @param {boolean} [capitalize=true] - If set to true, returns string in CamelCase.
* @param {number} [wordCount=3] - The number of words to use in the URL.
* @param {string} [seperator=''] - The word seperator.
*/
function readable(capitalize=true, wordCount=3, seperator='') {
if (wordCount < 2) {
throw new Error('Minimum value expected: 2');
}
else if (wordCount > 10) {
throw new Error('Maximum value expected: 10');
}
this.capitalize = capitalize;
this.wordCount = wordCount;
this.seperator = seperator
this.vowels = ['a', 'e', 'i', 'o', 'u'];
this.adjectives = [...adjectives];
this.nouns = [...nouns];
}
/**
* Converts each word in list to title case.
* @param {string[]} wordsList - The array of words to be capitalized.
* @returns {string[]} - The array with each word capitalized.
*/
readable.prototype.convertToTitleCase = function (wordsList) {
for (var i = 0; i < wordsList.length; i++) {
wordsList[i] = wordsList[i].charAt(0).toUpperCase() + wordsList[i].slice(1).toLowerCase();
}
return wordsList;
}
/**
* Generates the string.
* @returns {string} - The randomly generated string.
*/
readable.prototype.generate = function () {
wordsList = [];
wordsList.push(this.adjectives[Math.floor(Math.random() * this.adjectives.length)]);
wordsList.push(this.nouns[Math.floor(Math.random() * this.nouns.length)]);
if (this.wordCount > 5){
for (var i = 0; i < this.wordCount - 2; i++) {
wordsList.unshift(this.adjectives[Math.floor(Math.random() * this.adjectives.length)]);
}
}
else {
if (this.wordCount > 2) {
wordsList.unshift(this.adjectives[Math.floor(Math.random() * this.adjectives.length)]);
}
if (this.wordCount > 3) {
var isVowel = false;
var firstLetter = wordsList[0][0];
for(var i = 0; i < 5; i++)
{
if (this.vowels[i] === firstLetter) {
isVowel = true;
break;
}
}
if (isVowel) {
wordsList.unshift('an');
}
else {
wordsList.unshift(['a', 'the'][Math.floor(Math.random() * 2)]);
}
}
if (this.wordCount > 4) {
wordsList.splice(2, 0, 'and');
}
}
if (this.capitalize) {
wordsList = this.convertToTitleCase(wordsList);
}
return wordsList.join(this.seperator);
}
module.exports = readable;