blindtext.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * A blindtext generator written in JavaScript. It uses a set of latin words to create either a given amount
  3. * of words or sentences.
  4. *
  5. * @author mightyplow
  6. */
  7. const defaultOptions = {
  8. minWords: 3,
  9. maxWords: 9,
  10. availableWords: require('./words'),
  11. punctuationMarks: ['.', '!', '?']
  12. };
  13. const {
  14. randomInt,
  15. capitalize,
  16. getRandomArrayValue
  17. } = require('./utils');
  18. function getRandomWord ({ availableWords}) {
  19. return getRandomArrayValue(availableWords);
  20. }
  21. function createSentence ({ minWords, maxWords, availableWords, punctuationMarks }) {
  22. const numWords = randomInt(minWords, maxWords);
  23. const sentenceWords = [];
  24. for (let i = 0, randomWord = ''; i < numWords; i += 1) {
  25. do {
  26. randomWord = getRandomWord({ availableWords });
  27. } while(sentenceWords.includes(randomWord));
  28. // capitalize first letter when first word of sentence
  29. // also capitalize when a random number between 0 and 3 is 0 -> just to get more capital letters
  30. sentenceWords.push(
  31. (i !== 0 && randomInt(0, 3) > 0)
  32. ? randomWord
  33. : capitalize(randomWord)
  34. );
  35. }
  36. return sentenceWords.join(' ') + getRandomArrayValue(punctuationMarks);
  37. }
  38. const Unit = {
  39. SENTENCE: 'sentence',
  40. WORD: 'word'
  41. };
  42. const UnitFunction = {
  43. [Unit.SENTENCE]: createSentence,
  44. [Unit.WORD]: getRandomWord
  45. };
  46. function createText (num, unit = Unit.WORD, options) {
  47. if (!UnitFunction.hasOwnProperty(unit)) {
  48. throw Error('Invalid unit parameter');
  49. }
  50. const creatorOptions = Object.assign({}, options, defaultOptions);
  51. const unitCreator = UnitFunction[unit];
  52. const texts = [];
  53. for (let i = 0; i < num; i += 1) {
  54. texts.push(unitCreator(creatorOptions));
  55. }
  56. return texts.join(' ');
  57. }
  58. export {
  59. createText,
  60. Unit
  61. };