« get me outta code hell

wrap.js « util - tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
path: root/util/wrap.js
blob: 78e5233704e5cafd42ee7cd3020692f6e8508fb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module.exports = function wrap(str, width) {
  // Wraps a string into separate lines. Returns an array of strings, for
  // each line of the text.

  const lines = []
  const words = str.split(' ')

  let curLine = words[0]

  for (let word of words.slice(1)) {
    if (curLine.length + word.length > width) {
      lines.push(curLine)
      curLine = word
    } else {
      curLine += ' ' + word
    }
  }

  lines.push(curLine)

  return lines
}