Skip to content

Commit

Permalink
Added options.type and options.format
Browse files Browse the repository at this point in the history
options.type is a string that defines how the result array will be populated. ( I implemented the "PAIRS" type ).
options.format is a string that defines how words will be formatted. (I implemented the "PASCALCASE" type).
if type and format are not defined or are different than any case in the switch statements, than it all works as default.

I implemented this because I published an article on medium, I made a React Native version of the Flutter's "Write your first Flutter app". ( you can find it here: https://medium.com/@mattveraldi/flutter-write-your-first-flutter-app-in-react-native-1e468ab8655b ).
I used a function on top of random-words to do the same thing that english_words Flutter's package does. So I thought to make a pull request so anyone can use it.
  • Loading branch information
mattveraldi authored Apr 7, 2018
1 parent 1318a27 commit 084702c
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,32 @@ function words(options) {
return Math.floor(Math.random() * lessThan);
}

function formatter(word){
switch(options.format.toUpperCase()){
case "PASCALCASE":
return word.toString().slice(0,1).toUpperCase().concat(word.toString().slice(1))
default:
return word;
}
}

function defaultPopulator(){
for (var i = 0; (i < total); i++) {
results.push(formatter( word() ));
}
}

function pairsPopulator(){
var token='';
for(var i = 0; i < (total*2); i++){
token += formatter( generateRandomWord() );
if ((i+1) % 2 === 0) {
results.push(token);
token = "";
}
}
}

// No arguments = generate one word
if (typeof(options) === 'undefined') {
return word();
Expand All @@ -287,6 +313,16 @@ function words(options) {
options = { exactly: options };
}

//if type is undefined set it to 'null'
if(typeof(options.type) === 'undefined') {
options.type = 'null';
}

//if no format is requested set it to 'null'
if(typeof(options.format) === 'undefined') {
options.format = 'null';
}

// options supported: exactly, min, max, join
if (options.exactly) {
options.min = options.exactly;
Expand All @@ -295,16 +331,25 @@ function words(options) {
var total = options.min + randInt(options.max + 1 - options.min);
var results = [];

for (var i = 0; (i < total); i++) {
results.push(word());
var type = options.type.toUpperCase();

switch(type){
case "PAIRS":
pairsPopulator();
break;
default:
defaultPopulator();
break;
}

if (options.join) {
results = results.join(options.join);
}

return results;
}


module.exports = words;
// Export the word list as it is often useful
words.wordList = wordList;
Expand Down

0 comments on commit 084702c

Please sign in to comment.