« 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: 3c381d4d1995bb61c9e1e14a2d9ba55b590f0018 (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 (const word of words.slice(1)) {
    if (curLine.length + word.length > width) {
      lines.push(curLine)
      curLine = word
    } else {
      curLine += ' ' + word
    }
  }

  lines.push(curLine)

  return lines
}