« 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: 2c720c868aff65457f5a613dd48312f556e5c6bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export default 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
}