Advertisement
beau_mollet

Place Words in a Old School Grid Layout

Jan 27th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const ROW_LIMIT = 15;
  2.  
  3. const text = "this is an Example Hello how are you today gentlemen life is life nanana na na na"
  4.  
  5. class Row {
  6.     constructor() {
  7.         this.Words = []
  8.         this.NumberOfWords = 0
  9.         this.NumberOfWhitespaces = 0
  10.         this.Length = 0
  11.     }
  12.     wrap(text) {
  13.         if( ((this.Length + this.NumberOfWhitespaces) + text.length) >= ROW_LIMIT) {
  14.             return true
  15.         }
  16.     }
  17.     addWhitespace() {
  18.         if(this.NumberOfWords > 1)
  19.             this.NumberOfWhitespaces++
  20.     }
  21.     addWord(text) {
  22.         this.Words.push(text)
  23.         this.Length += text.length
  24.         this.NumberOfWords++
  25.         this.addWhitespace()
  26.  
  27.     }
  28. }
  29.  
  30. class Grid {
  31.     constructor(row_length, text) {
  32.         this.rows = []
  33.         this.row_max_length = row_length
  34.         this.Text = text
  35.         this.words = text.split(' ')
  36.         this.RowBuilder()
  37.     }
  38.     RowBuilder() {
  39.         var row = new Row()
  40.  
  41.         for(let word of this.words) {
  42.             if(row.wrap(word)) {
  43.                 this.rows.push(row)
  44.                 row = new Row()
  45.             }
  46.             row.addWord(word)
  47.         }
  48.         this.rows.push(row)
  49.     }
  50. }
  51.  
  52. var grid = new Grid(ROW_LIMIT, text)
  53. console.log(grid.rows)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement