123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- /**
- * A blindtext generator written in JavaScript. It uses a set of latin words to create either a given amount
- * of words or sentences.
- *
- * @author mightyplow
- */
- const defaultOptions = {
- minWords: 3,
- maxWords: 9,
- availableWords: require('./words'),
- punctuationMarks: ['.', '!', '?']
- };
- const {
- randomInt,
- capitalize,
- getRandomArrayValue
- } = require('./utils');
- function getRandomWord ({ availableWords}) {
- return getRandomArrayValue(availableWords);
- }
- 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({ availableWords });
- } while(sentenceWords.includes(randomWord));
- // capitalize first letter when first word of sentence
- // also capitalize when a random number between 0 and 3 is 0 -> just to get more capital letters
- sentenceWords.push(
- (i !== 0 && randomInt(0, 3) > 0)
- ? randomWord
- : capitalize(randomWord)
- );
- }
- return sentenceWords.join(' ') + getRandomArrayValue(punctuationMarks);
- }
- const Unit = {
- SENTENCE: 'sentence',
- WORD: 'word'
- };
- const UnitFunction = {
- [Unit.SENTENCE]: createSentence,
- [Unit.WORD]: getRandomWord
- };
- function createText (num, unit = Unit.WORD, options) {
- if (!UnitFunction.hasOwnProperty(unit)) {
- throw Error('Invalid unit parameter');
- }
- const creatorOptions = Object.assign({}, options, defaultOptions);
- const unitCreator = UnitFunction[unit];
- const texts = [];
- for (let i = 0; i < num; i += 1) {
- texts.push(unitCreator(creatorOptions));
- }
- return texts.join(' ');
- }
- export {
- createText,
- Unit
- };
|