浏览代码

check array before value extraction

mightyplow 6 年之前
父节点
当前提交
c2dd29c43a
共有 2 个文件被更改,包括 13 次插入9 次删除
  1. 9 9
      blindtext.js
  2. 4 0
      utils.js

+ 9 - 9
blindtext.js

@@ -7,28 +7,28 @@
 
 const defaultOptions = {
     minWords: 3,
-    maxWords: 9
+    maxWords: 9,
+    availableWords: require('./words'),
+    punctuationMarks: ['.', '!', '?']
 };
 
-const availableWords = require('./words');
-const punctuationMarks = ['.', '!', '?'];
-
 const {
     randomInt,
     capitalize,
     getRandomArrayValue
 } = require('./utils');
 
-const getRandomPunctuationMark = getRandomArrayValue.bind(null, punctuationMarks);
-const getRandomWord = getRandomArrayValue.bind(null, availableWords);
+function getRandomWord ({ availableWords}) {
+    return getRandomArrayValue(availableWords);
+}
 
-function createSentence ({ minWords, maxWords }) {
+function createSentence ({ minWords, maxWords, availableWords, punctuationMarks }) {
     const numWords = randomInt(minWords, maxWords);
     const sentenceWords = [];
 
     for (let i = 0, randomWord = ''; i < numWords; i += 1) {
         do {
-            randomWord = getRandomWord();
+            randomWord = getRandomWord({ availableWords });
         } while(sentenceWords.includes(randomWord));
 
         // capitalize first letter when first word of sentence
@@ -40,7 +40,7 @@ function createSentence ({ minWords, maxWords }) {
         );
     }
 
-    return sentenceWords.join(' ') + getRandomPunctuationMark();
+    return sentenceWords.join(' ') + getRandomArrayValue(punctuationMarks);
 }
 
 const Unit = {

+ 4 - 0
utils.js

@@ -3,6 +3,10 @@ function randomInt (min, max) {
 }
 
 function getRandomArrayValue (source) {
+    if (!(source && source.length)) {
+        return;
+    }
+
     const randomIndex = randomInt(0, source.length - 1);
     return source[randomIndex];
 }