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. };
  11. const availableWords = require('./words');
  12. const punctuationMarks = ['.', '!', '?'];
  13. const {
  14. randomInt,
  15. capitalize,
  16. getRandomArrayValue
  17. } = require('./utils');
  18. const getRandomPunctuationMark = getRandomArrayValue.bind(null, punctuationMarks);
  19. const getRandomWord = getRandomArrayValue.bind(null, availableWords);
  20. function createSentence ({ minWords, maxWords }) {
  21. const numWords = randomInt(minWords, maxWords);
  22. const sentenceWords = [];
  23. for (let i = 0, randomWord = ''; i < numWords; i += 1) {
  24. do {
  25. randomWord = getRandomWord();
  26. } while(sentenceWords.includes(randomWord));
  27. // capitalize first letter when first word of sentence
  28. // also capitalize when a random number between 0 and 3 is 0 -> just to get more capital letters
  29. sentenceWords.push(
  30. (i !== 0 && randomInt(0, 3) > 0)
  31. ? randomWord
  32. : capitalize(randomWord)
  33. );
  34. }
  35. return sentenceWords.join(' ') + getRandomPunctuationMark();
  36. }
  37. const Unit = {
  38. SENTENCE: 'sentence',
  39. WORD: 'word'
  40. };
  41. const UnitFunction = {
  42. [Unit.SENTENCE]: createSentence,
  43. [Unit.WORD]: getRandomWord
  44. };
  45. function createText (num, unit = Unit.WORD, options) {
  46. if (!UnitFunction.hasOwnProperty(unit)) {
  47. throw Error('Invalid unit parameter');
  48. }
  49. const creatorOptions = Object.assign({}, options, defaultOptions);
  50. const unitCreator = UnitFunction[unit];
  51. const texts = [];
  52. for (let i = 0; i < num; i += 1) {
  53. texts.push(unitCreator(creatorOptions));
  54. }
  55. return texts.join(' ');
  56. }
  57. export {
  58. createText,
  59. Unit
  60. };