« 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: 71a1f1cd6416d8024e5d90788d49893bfa480339 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const ansi = require('./ansi')

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]
  let curColumns = ansi.measureColumns(curLine)

  for (const word of words.slice(1)) {
    const wordColumns = ansi.measureColumns(word)
    if (curColumns + wordColumns > width) {
      lines.push(curLine)
      curLine = word
      curColumns = wordColumns
    } else {
      curLine += ' ' + word
      curColumns += 1 + wordColumns
    }
  }

  lines.push(curLine)

  return lines
}