Launch Week Day 3: Introducing Organization Notifications in Socket.Learn More
Socket
Book a DemoSign in
Socket

wordwrapjs

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

wordwrapjs - npm Package Compare versions

Comparing version
1.2.1
to
2.0.0-0
+123
es5/lib/wordwrapjs.js
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var os = require('os');
var t = require('typical');
var re = {
chunk: /[^\s-]+?-\b|\S+|\s+|\r\n?|\n/g,
ansiEscapeSequence: /\u001b.*?m/g
};
var WordWrap = function () {
function WordWrap(text, options) {
_classCallCheck(this, WordWrap);
options = options || {};
if (!t.isDefined(text)) text = '';
this._lines = String(text).split(/\r\n|\n/g);
this.options = options;
this.options.width = options.width === undefined ? 30 : options.width;
}
_createClass(WordWrap, [{
key: 'lines',
value: function lines() {
var _this = this;
var flatten = require('reduce-flatten');
return this._lines.map(trimLine.bind(this)).map(function (line) {
return line.match(re.chunk) || ['~~empty~~'];
}).map(function (lineWords) {
if (_this.options.break) {
return lineWords.map(breakWord.bind(_this));
} else {
return lineWords;
}
}).map(function (lineWords) {
return lineWords.reduce(flatten, []);
}).map(function (lineWords) {
return lineWords.reduce(function (lines, word) {
var currentLine = lines[lines.length - 1];
if (replaceAnsi(word).length + replaceAnsi(currentLine).length > _this.options.width) {
lines.push(word);
} else {
lines[lines.length - 1] += word;
}
return lines;
}, ['']);
}).reduce(flatten, []).map(trimLine.bind(this)).filter(function (line) {
return line.trim();
}).map(function (line) {
return line.replace('~~empty~~', '');
});
}
}, {
key: 'wrap',
value: function wrap() {
return this.lines().join(os.EOL);
}
}, {
key: 'toString',
value: function toString() {
return this.wrap();
}
}], [{
key: 'wrap',
value: function wrap(text, options) {
var block = new this(text, options);
return block.wrap();
}
}, {
key: 'lines',
value: function lines(text, options) {
var block = new this(text, options);
return block.lines();
}
}, {
key: 'isWrappable',
value: function isWrappable(text) {
if (t.isDefined(text)) {
text = String(text);
var matches = text.match(re.chunk);
return matches ? matches.length > 1 : false;
}
}
}, {
key: 'getChunks',
value: function getChunks(text) {
return text.match(re.chunk) || [];
}
}]);
return WordWrap;
}();
function trimLine(line) {
return this.options.noTrim ? line : line.trim();
}
function replaceAnsi(string) {
return string.replace(re.ansiEscapeSequence, '');
}
function breakWord(word) {
if (replaceAnsi(word).length > this.options.width) {
var letters = word.split('');
var piece = void 0;
var pieces = [];
while ((piece = letters.splice(0, this.options.width)).length) {
pieces.push(piece.join(''));
}
return pieces;
} else {
return word;
}
}
module.exports = WordWrap;
'use strict';
var TestRunner = require('test-runner');
var wordwrap = require('../../');
var a = require('core-assert');
var runner = new TestRunner();
var bars = "I'm rapping. I'm rapping. I'm rap rap rapping. I'm rap rap rap rap rappity rapping.";
runner.test('simple', function () {
a.strictEqual(wordwrap.wrap(bars), "I'm rapping. I'm rapping. I'm\nrap rap rapping. I'm rap rap\nrap rap rappity rapping.");
});
runner.test('width', function () {
a.strictEqual(wordwrap.wrap(bars, { width: 3 }), "I'm\nrapping.\nI'm\nrapping.\nI'm\nrap\nrap\nrapping.\nI'm\nrap\nrap\nrap\nrap\nrappity\nrapping.");
});
runner.skip('ignore', function () {
a.strictEqual(wrap(bars, { ignore: "I'm" }), "I'm rapping. I'm rapping. I'm rap rap\nrapping. I'm rap rap rap rap\nrappity rapping.");
});
runner.test('wordwrap.lines', function () {
a.deepStrictEqual(wordwrap.lines(bars), ["I'm rapping. I'm rapping. I'm", "rap rap rapping. I'm rap rap", 'rap rap rappity rapping.']);
});
runner.test('wordwrap.lines, width', function () {
a.deepStrictEqual(wordwrap.lines(bars, { width: 3 }), ["I'm", 'rapping.', "I'm", 'rapping.', "I'm", 'rap', 'rap', 'rapping.', "I'm", 'rap', 'rap', 'rap', 'rap', 'rappity', 'rapping.']);
});
runner.test('wordwrap.lines, width smaller than content width', function () {
a.deepStrictEqual(wordwrap.lines('4444', { width: 3 }), ['4444']);
a.deepStrictEqual(wordwrap.lines('onetwothreefour fivesixseveneight', { width: 7 }), ['onetwothreefour', 'fivesixseveneight']);
});
runner.test('wordwrap.lines, break', function () {
a.deepStrictEqual(wordwrap.lines('onetwothreefour', { width: 7, break: true }), ['onetwot', 'hreefou', 'r']);
a.deepStrictEqual(wordwrap.lines('\x1B[4m--------\x1B[0m', { width: 10, break: true, ignore: /\u001b.*?m/g }), ['\x1B[4m--------\x1B[0m']);
a.deepStrictEqual(wordwrap.lines('onetwothreefour fivesixseveneight', { width: 7, break: true }), ['onetwot', 'hreefou', 'r', 'fivesix', 'sevenei', 'ght']);
});
runner.test('wordwrap.lines(text): respect existing linebreaks', function () {
a.deepStrictEqual(wordwrap.lines('one\ntwo three four', { width: 8 }), ['one', 'two', 'three', 'four']);
a.deepStrictEqual(wordwrap.lines('one \n \n two three four', { width: 8 }), ['one', '', 'two', 'three', 'four']);
a.deepStrictEqual(wordwrap.lines('one\r\ntwo three four', { width: 8 }), ['one', 'two', 'three', 'four']);
});
runner.test('wordwrap.lines(text): multilingual', function () {
a.deepStrictEqual(wordwrap.lines('Può parlare più lentamente?', { width: 10 }), ['Può', 'parlare', 'più', 'lentamente?']);
a.deepStrictEqual(wordwrap.lines('один два три', { width: 4 }), ['один', 'два', 'три']);
});
runner.test('wrap hyphenated words', function () {
a.deepStrictEqual(wordwrap.lines('ones-and-twos', { width: 5 }), ['ones-', 'and-', 'twos']);
a.deepStrictEqual(wordwrap.lines('ones-and-twos', { width: 10 }), ['ones-and-', 'twos']);
a.deepStrictEqual(wordwrap.lines('--------', { width: 5 }), ['--------']);
a.deepStrictEqual(wordwrap.lines('--one --fifteen', { width: 5 }), ['--one', '--fifteen']);
a.deepStrictEqual(wordwrap.lines('one-two', { width: 10 }), ['one-two']);
a.deepStrictEqual(wordwrap.lines('ansi-escape-sequences', { width: 22 }), ['ansi-escape-sequences']);
a.deepStrictEqual(wordwrap.lines('one - two'), ['one - two']);
});
runner.test('isWrappable(input)', function () {
a.strictEqual(wordwrap.isWrappable('one two'), true);
a.strictEqual(wordwrap.isWrappable('one-two'), true);
a.strictEqual(wordwrap.isWrappable('one\ntwo'), true);
});
runner.test('getChunks', function () {
a.deepStrictEqual(wordwrap.getChunks('one two three'), ['one', ' ', 'two', ' ', 'three']);
});
runner.test('noTrim', function () {
a.deepStrictEqual(wordwrap.lines('word\n - word\n - word'), ['word', '- word', '- word']);
a.deepStrictEqual(wordwrap.lines('word\n - word\n - word', { noTrim: true }), ['word', ' - word', ' - word']);
});
runner.test('wrapping text containing ansi escape sequences', function () {
a.deepStrictEqual(wordwrap.wrap('Generates something \x1B[3mvery\x1B[0m important.', { width: 35 }), 'Generates something \x1B[3mvery\x1B[0m important.');
});
'use strict';
var TestRunner = require('test-runner');
var TextBlock = require('../../');
var a = require('core-assert');
var runner = new TestRunner();
runner.test('non-string input', function () {
a.strictEqual(TextBlock.wrap(undefined), '');
a.strictEqual(TextBlock.wrap(function () {}), 'function () {}');
a.strictEqual(TextBlock.wrap({}), '[object Object]');
a.strictEqual(TextBlock.wrap(null), 'null');
a.strictEqual(TextBlock.wrap(true), 'true');
a.strictEqual(TextBlock.wrap(0), '0');
a.strictEqual(TextBlock.wrap(NaN), 'NaN');
a.strictEqual(TextBlock.wrap(Infinity), 'Infinity');
});
'use strict'
var detect = require('feature-detect-es6')
if (detect.all('class', 'arrowFunction', 'let', 'const')) {
module.exports = require('./src/lib/wordwrapjs')
} else {
module.exports = require('./es5/lib/wordwrapjs')
}
'use strict'
const os = require('os')
const t = require('typical')
/**
* @module wordwrapjs
*/
const re = {
chunk: /[^\s-]+?-\b|\S+|\s+|\r\n?|\n/g,
ansiEscapeSequence: /\u001b.*?m/g
}
/**
* @alias module:wordwrapjs
* @typicalname wordwrap
*/
class WordWrap {
constructor (text, options) {
options = options || {}
if (!t.isDefined(text)) text = ''
this._lines = String(text).split(/\r\n|\n/g)
this.options = options
this.options.width = options.width === undefined ? 30 : options.width
}
lines () {
const flatten = require('reduce-flatten')
/* trim each line of the supplied text */
return this._lines.map(trimLine.bind(this))
/* split each line into an array of chunks, else mark it empty */
.map(line => line.match(re.chunk) || [ '~~empty~~' ])
/* optionally, break each word on the line into pieces */
.map(lineWords => {
if (this.options.break) {
return lineWords.map(breakWord.bind(this))
} else {
return lineWords
}
})
.map(lineWords => lineWords.reduce(flatten, []))
/* transforming the line of words to one or more new lines wrapped to size */
.map(lineWords => {
return lineWords
.reduce((lines, word) => {
let currentLine = lines[lines.length - 1]
if (replaceAnsi(word).length + replaceAnsi(currentLine).length > this.options.width) {
lines.push(word)
} else {
lines[lines.length - 1] += word
}
return lines
}, [ '' ])
})
.reduce(flatten, [])
/* trim the wrapped lines */
.map(trimLine.bind(this))
/* filter out empty lines */
.filter(line => line.trim())
/* restore the user's original empty lines */
.map(line => line.replace('~~empty~~', ''))
}
wrap () {
return this.lines().join(os.EOL)
}
toString () {
return this.wrap()
}
/**
* @param {string} - the input text to wrap
* @param [options] {object} - optional configuration
* @param [options.width] {number} - the max column width in characters (defaults to 30).
* @param [options.break] {boolean} - if true, words exceeding the specified `width` will be forcefully broken
* @param [options.noTrim] {boolean} - By default, each line output is trimmed. If `noTrim` is set, no line-trimming occurs - all whitespace from the input text is left in.
* @return {string}
*/
static wrap (text, options) {
const block = new this(text, options)
return block.wrap()
}
/**
* Wraps the input text, returning an array of strings (lines).
* @param {string} - input text
* @param {object} - Accepts same options as constructor.
*/
static lines (text, options) {
const block = new this(text, options)
return block.lines()
}
/**
* Returns true if the input text would be wrapped if passed into `.wrap()`.
* @param {string} - input text
* @return {boolean}
*/
static isWrappable (text) {
if (t.isDefined(text)) {
text = String(text)
var matches = text.match(re.chunk)
return matches ? matches.length > 1 : false
}
}
/**
* Splits the input text into an array of words and whitespace.
* @param {string} - input text
* @returns {string[]}
*/
static getChunks (text) {
return text.match(re.chunk) || []
}
}
function trimLine (line) {
return this.options.noTrim ? line : line.trim()
}
function replaceAnsi (string) {
return string.replace(re.ansiEscapeSequence, '')
}
/* break a word into several pieces */
function breakWord (word) {
if (replaceAnsi(word).length > this.options.width) {
const letters = word.split('')
let piece
const pieces = []
while ((piece = letters.splice(0, this.options.width)).length) {
pieces.push(piece.join(''))
}
return pieces
} else {
return word
}
}
module.exports = WordWrap
'use strict'
var TestRunner = require('test-runner')
var wordwrap = require('../../')
var a = require('core-assert')
var runner = new TestRunner()
var bars = "I'm rapping. I'm rapping. I'm rap rap rapping. I'm rap rap rap rap rappity rapping."
runner.test('simple', function () {
a.strictEqual(
wordwrap.wrap(bars),
"I'm rapping. I'm rapping. I'm\nrap rap rapping. I'm rap rap\nrap rap rappity rapping."
)
})
runner.test('width', function () {
a.strictEqual(
wordwrap.wrap(bars, { width: 3 }),
"I'm\nrapping.\nI'm\nrapping.\nI'm\nrap\nrap\nrapping.\nI'm\nrap\nrap\nrap\nrap\nrappity\nrapping."
)
})
runner.skip('ignore', function () {
a.strictEqual(
wrap(bars, { ignore: "I'm" }),
"I'm rapping. I'm rapping. I'm rap rap\nrapping. I'm rap rap rap rap\nrappity rapping."
)
})
runner.test('wordwrap.lines', function () {
a.deepStrictEqual(
wordwrap.lines(bars),
[ "I'm rapping. I'm rapping. I'm",
"rap rap rapping. I'm rap rap",
'rap rap rappity rapping.' ]
)
})
runner.test('wordwrap.lines, width', function () {
a.deepStrictEqual(
wordwrap.lines(bars, { width: 3 }),
[ "I'm",
'rapping.',
"I'm",
'rapping.',
"I'm",
'rap',
'rap',
'rapping.',
"I'm",
'rap',
'rap',
'rap',
'rap',
'rappity',
'rapping.' ]
)
})
runner.test('wordwrap.lines, width smaller than content width', function () {
a.deepStrictEqual(
wordwrap.lines('4444', { width: 3 }),
[ '4444' ]
)
a.deepStrictEqual(
wordwrap.lines('onetwothreefour fivesixseveneight', { width: 7 }),
[ 'onetwothreefour', 'fivesixseveneight' ]
)
})
runner.test('wordwrap.lines, break', function () {
a.deepStrictEqual(
wordwrap.lines('onetwothreefour', { width: 7, break: true }),
[ 'onetwot', 'hreefou', 'r' ]
)
a.deepStrictEqual(
wordwrap.lines('\u001b[4m--------\u001b[0m', { width: 10, break: true, ignore: /\u001b.*?m/g }),
[ '\u001b[4m--------\u001b[0m' ]
)
a.deepStrictEqual(
wordwrap.lines(
'onetwothreefour fivesixseveneight',
{ width: 7, break: true }
),
[ 'onetwot', 'hreefou', 'r', 'fivesix', 'sevenei', 'ght' ]
)
})
runner.test('wordwrap.lines(text): respect existing linebreaks', function () {
a.deepStrictEqual(
wordwrap.lines('one\ntwo three four', { width: 8 }),
[ 'one', 'two', 'three', 'four' ]
)
a.deepStrictEqual(
wordwrap.lines('one \n \n two three four', { width: 8 }),
[ 'one', '', 'two', 'three', 'four' ]
)
a.deepStrictEqual(
wordwrap.lines('one\r\ntwo three four', { width: 8 }),
[ 'one', 'two', 'three', 'four' ]
)
})
runner.test('wordwrap.lines(text): multilingual', function () {
a.deepStrictEqual(
wordwrap.lines('Può parlare più lentamente?', { width: 10 }),
[ 'Può', 'parlare', 'più', 'lentamente?' ]
)
a.deepStrictEqual(
wordwrap.lines('один два три', { width: 4 }),
[ 'один', 'два', 'три' ]
)
})
runner.test('wrap hyphenated words', function () {
a.deepStrictEqual(
wordwrap.lines('ones-and-twos', { width: 5 }),
[ 'ones-', 'and-', 'twos' ]
)
a.deepStrictEqual(
wordwrap.lines('ones-and-twos', { width: 10 }),
[ 'ones-and-', 'twos' ]
)
a.deepStrictEqual(
wordwrap.lines('--------', { width: 5 }),
[ '--------' ]
)
a.deepStrictEqual(
wordwrap.lines('--one --fifteen', { width: 5 }),
[ '--one', '--fifteen' ]
)
a.deepStrictEqual(
wordwrap.lines('one-two', { width: 10 }),
[ 'one-two' ]
)
a.deepStrictEqual(
wordwrap.lines('ansi-escape-sequences', { width: 22 }),
[ 'ansi-escape-sequences' ]
)
a.deepStrictEqual(
wordwrap.lines('one - two'),
[ 'one - two' ]
)
})
runner.test('isWrappable(input)', function () {
a.strictEqual(wordwrap.isWrappable('one two'), true)
a.strictEqual(wordwrap.isWrappable('one-two'), true)
a.strictEqual(wordwrap.isWrappable('one\ntwo'), true)
})
runner.test('getChunks', function () {
a.deepStrictEqual(wordwrap.getChunks('one two three'), [ 'one', ' ', 'two', ' ', 'three' ])
})
runner.test('noTrim', function () {
a.deepStrictEqual(wordwrap.lines('word\n - word\n - word'), [
'word', '- word', '- word'
])
a.deepStrictEqual(wordwrap.lines('word\n - word\n - word', { noTrim: true }), [
'word', ' - word', ' - word'
])
})
runner.test('wrapping text containing ansi escape sequences', function () {
a.deepStrictEqual(
wordwrap.wrap('Generates something \u001b[3mvery\u001b[0m important.', { width: 35 }),
'Generates something \u001b[3mvery\u001b[0m important.'
)
})
'use strict'
var TestRunner = require('test-runner')
var TextBlock = require('../../')
var a = require('core-assert')
var runner = new TestRunner()
runner.test('non-string input', function () {
a.strictEqual(TextBlock.wrap(undefined), '')
a.strictEqual(TextBlock.wrap(function () {}), 'function () {}')
a.strictEqual(TextBlock.wrap({}), '[object Object]')
a.strictEqual(TextBlock.wrap(null), 'null')
a.strictEqual(TextBlock.wrap(true), 'true')
a.strictEqual(TextBlock.wrap(0), '0')
a.strictEqual(TextBlock.wrap(NaN), 'NaN')
a.strictEqual(TextBlock.wrap(Infinity), 'Infinity')
})
'use strict'
var detect = require('feature-detect-es6')
var TestRunner = require('test-runner')
if (detect.all('class', 'arrowFunction', 'let', 'const')) {
TestRunner.run('src/test/*.js')
} else {
TestRunner.run('es5/test/*.js')
}
+1
-1
language: node_js
node_js:
- 7
- 6

@@ -8,2 +9,1 @@ - 5

- 0.12
- '0.10'

@@ -7,6 +7,55 @@ [![view on npm](http://img.shields.io/npm/v/wordwrapjs.svg)](https://www.npmjs.org/package/wordwrapjs)

{{>main}}
# wordwrapjs
Word wrapping, with a few features.
- force-break option
- wraps hypenated words
- multilingual - wraps any language that uses whitespace for word separation.
## Synopsis
Wrap some text in a 20 character column.
```js
> wordwrap = require('wordwrapjs')
> text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
> result = wordwrap.wrap(text, { width: 20 })
```
`result` now looks like this:
```
Lorem ipsum dolor
sit amet,
consectetur
adipiscing elit, sed
do eiusmod tempor
incididunt ut labore
et dolore magna
aliqua.
```
By default, long words will not break. Unless you set the `break` option.
```js
> url = 'https://github.com/75lb/wordwrapjs'
> wrap.lines(url, { width: 18 })
[ 'https://github.com/75lb/wordwrapjs' ]
> wrap.lines(url, { width: 18, break: true })
[ 'https://github.com', '/75lb/wordwrapjs' ]
```
## API Reference
{{#module name="wordwrapjs"}}
{{>body~}}
{{>member-index~}}
{{>members~}}
{{/module}}
* * *
&copy; 2015-16 Lloyd Brookes \<75pound@gmail.com\>. Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).
{
"name": "wordwrapjs",
"author": "Lloyd Brookes <75pound@gmail.com>",
"version": "1.2.1",
"version": "2.0.0-0",
"description": "Word-wrapping for javascript.",
"repository": "https://github.com/75lb/wordwrapjs.git",
"license": "MIT",
"main": "./lib/wordwrapjs.js",
"main": "index.js",
"keywords": [

@@ -17,17 +17,21 @@ "word",

"engines": {
"node": ">=0.10.0"
"node": ">=0.12.0"
},
"scripts": {
"test": "test-runner test/*.js",
"docs": "jsdoc2md -t jsdoc2md/README.hbs lib/*.js > README.md; echo"
"test": "node test.js",
"docs": "jsdoc2md -t jsdoc2md/README.hbs src/lib/*.js > README.md; echo",
"es5": "rm -rf es5 && babel --presets babel-preset-es2015 --no-comments src --out-dir es5"
},
"devDependencies": {
"core-assert": "^0.2.0",
"jsdoc-to-markdown": "^2.0.0-alpha",
"test-runner": "~0.1.9"
"babel-preset-es2015": "^6.18.0",
"core-assert": "^0.2.1",
"jsdoc-to-markdown": "^2.0.1",
"test-runner": "~0.2.5"
},
"dependencies": {
"array-back": "^1.0.3",
"typical": "^2.5.0"
"feature-detect-es6": "^1.3.1",
"reduce-flatten": "^1.0.1",
"typical": "^2.6.0"
}
}
+56
-54

@@ -7,20 +7,20 @@ [![view on npm](http://img.shields.io/npm/v/wordwrapjs.svg)](https://www.npmjs.org/package/wordwrapjs)

<a name="module_wordwrapjs"></a>
# wordwrapjs
## wordwrapjs
Word wrapping, with a few features.
- multilingual - wraps any language using whitespace word separation.
- force-break option
- ignore pattern option (e.g. ansi escape sequences)
- wraps hypenated words
- multilingual - wraps any language that uses whitespace for word separation.
**Example**
Wrap some sick bars in a 20 character column.
## Synopsis
Wrap some text in a 20 character column.
```js
> wrap = require("wordwrapjs")
> wordwrap = require('wordwrapjs')
> bars = "I'm rapping. I'm rapping. I'm rap rap rapping. I'm rap rap rap rap rappity rapping."
> result = wrap(bars, { width: 20 })
> text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
> result = wordwrap.wrap(text, { width: 20 })
```

@@ -30,12 +30,15 @@

```
I'm rapping. I'm
rapping. I'm rap rap
rapping. I'm rap rap
rap rap rappity
rapping.
Lorem ipsum dolor
sit amet,
consectetur
adipiscing elit, sed
do eiusmod tempor
incididunt ut labore
et dolore magna
aliqua.
```
By default, long words will not break. Unless you insist.
By default, long words will not break. Unless you set the `break` option.
```js
> url = "https://github.com/75lb/wordwrapjs"
> url = 'https://github.com/75lb/wordwrapjs'

@@ -49,48 +52,47 @@ > wrap.lines(url, { width: 18 })

## API Reference
* [wordwrapjs](#module_wordwrapjs)
* [wrap(text, [options])](#exp_module_wordwrapjs--wrap) ⇒ <code>string</code> ⏏
* [.lines(text, [options])](#module_wordwrapjs--wrap.lines) ⇒ <code>Array</code>
* [.isWrappable(text)](#module_wordwrapjs--wrap.isWrappable) ⇒ <code>boolean</code>
* [.getWords(text)](#module_wordwrapjs--wrap.getWords) ⇒ <code>Array.&lt;string&gt;</code>
* [WordWrap](#exp_module_wordwrapjs--WordWrap) ⏏
* [.wrap(text, [options])](#module_wordwrapjs--WordWrap.wrap) ⇒ <code>string</code>
* [.lines(text, options)](#module_wordwrapjs--WordWrap.lines)
* [.isWrappable(text)](#module_wordwrapjs--WordWrap.isWrappable) ⇒ <code>boolean</code>
* [.getChunks(text)](#module_wordwrapjs--WordWrap.getChunks) ⇒ <code>Array.&lt;string&gt;</code>
<a name="exp_module_wordwrapjs--wrap"></a>
<a name="exp_module_wordwrapjs--WordWrap"></a>
### wrap(text, [options]) ⇒ <code>string</code> ⏏
**Kind**: Exported function
### WordWrap ⏏
**Kind**: Exported class
<a name="module_wordwrapjs--WordWrap.wrap"></a>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| text | <code>string</code> | | the input text to wrap |
| [options] | <code>object</code> | | optional config |
| [options.width] | <code>number</code> | <code>30</code> | the max column width in characters |
| [options.ignore] | <code>RegExp</code> &#124; <code>Array.&lt;RegExp&gt;</code> | | one or more patterns to be ignored when sizing the newly wrapped lines. For example `ignore: /\u001b.*?m/g` will ignore unprintable ansi escape sequences. |
| [options.break] | <code>boolean</code> | | if true, words exceeding the specified `width` will be forcefully broken |
| [options.eol] | <code>string</code> | <code>&quot;os.EOL&quot;</code> | the desired new line character to use, defaults to [os.EOL](https://nodejs.org/api/os.html#os_os_eol). |
#### wordwrap.wrap(text, [options]) ⇒ <code>string</code>
**Kind**: static method of <code>[WordWrap](#exp_module_wordwrapjs--WordWrap)</code>
<a name="module_wordwrapjs--wrap.lines"></a>
| Param | Type | Description |
| --- | --- | --- |
| text | <code>string</code> | the input text to wrap |
| [options] | <code>object</code> | optional configuration |
| [options.width] | <code>number</code> | the max column width in characters (defaults to 30). |
| [options.break] | <code>boolean</code> | if true, words exceeding the specified `width` will be forcefully broken |
| [options.noTrim] | <code>boolean</code> | By default, each line output is trimmed. If `noTrim` is set, no line-trimming occurs - all whitespace from the input text is left in. |
#### wrap.lines(text, [options]) ⇒ <code>Array</code>
returns the wrapped output as an array of lines, rather than a single string
<a name="module_wordwrapjs--WordWrap.lines"></a>
**Kind**: static method of <code>[wrap](#exp_module_wordwrapjs--wrap)</code>
#### wordwrap.lines(text, options)
Wraps the input text, returning an array of strings (lines).
**Kind**: static method of <code>[WordWrap](#exp_module_wordwrapjs--WordWrap)</code>
| Param | Type | Description |
| --- | --- | --- |
| text | <code>string</code> | the input text to wrap |
| [options] | <code>object</code> | same options as [wrap](#module_wordwrapjs) |
| text | <code>string</code> | input text |
| options | <code>object</code> | Accepts same options as constructor. |
**Example**
```js
> bars = "I'm rapping. I'm rapping. I'm rap rap rapping. I'm rap rap rap rap rappity rapping."
> wrap.lines(bars)
[ "I'm rapping. I'm rapping. I'm",
"rap rap rapping. I'm rap rap",
"rap rap rappity rapping." ]
```
<a name="module_wordwrapjs--wrap.isWrappable"></a>
<a name="module_wordwrapjs--WordWrap.isWrappable"></a>
#### wrap.isWrappable(text) ⇒ <code>boolean</code>
Returns true if the input text is wrappable
#### wordwrap.isWrappable(text) ⇒ <code>boolean</code>
Returns true if the input text would be wrapped if passed into `.wrap()`.
**Kind**: static method of <code>[wrap](#exp_module_wordwrapjs--wrap)</code>
**Kind**: static method of <code>[WordWrap](#exp_module_wordwrapjs--WordWrap)</code>

@@ -101,8 +103,8 @@ | Param | Type | Description |

<a name="module_wordwrapjs--wrap.getWords"></a>
<a name="module_wordwrapjs--WordWrap.getChunks"></a>
#### wrap.getWords(text) ⇒ <code>Array.&lt;string&gt;</code>
Splits the input text returning an array of words
#### wordwrap.getChunks(text) ⇒ <code>Array.&lt;string&gt;</code>
Splits the input text into an array of words and whitespace.
**Kind**: static method of <code>[wrap](#exp_module_wordwrapjs--wrap)</code>
**Kind**: static method of <code>[WordWrap](#exp_module_wordwrapjs--WordWrap)</code>

@@ -116,2 +118,2 @@ | Param | Type | Description |

&copy; 2015 Lloyd Brookes \<75pound@gmail.com\>. Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).
&copy; 2015-16 Lloyd Brookes \<75pound@gmail.com\>. Documented by [jsdoc-to-markdown](https://github.com/jsdoc2md/jsdoc-to-markdown).
'use strict'
var arrayify = require('array-back')
var os = require('os')
var t = require('typical')
/**
Word wrapping, with a few features.
- multilingual - wraps any language using whitespace word separation.
- force-break option
- ignore pattern option (e.g. ansi escape sequences)
- wraps hypenated words
@module wordwrapjs
@example
Wrap some sick bars in a 20 character column.
```js
> wrap = require("wordwrapjs")
> bars = "I'm rapping. I'm rapping. I'm rap rap rapping. I'm rap rap rap rap rappity rapping."
> result = wrap(bars, { width: 20 })
```
`result` now looks like this:
```
I'm rapping. I'm
rapping. I'm rap rap
rapping. I'm rap rap
rap rap rappity
rapping.
```
By default, long words will not break. Unless you insist.
```js
> url = "https://github.com/75lb/wordwrapjs"
> wrap.lines(url, { width: 18 })
[ 'https://github.com/75lb/wordwrapjs' ]
> wrap.lines(url, { width: 18, break: true })
[ 'https://github.com', '/75lb/wordwrapjs' ]
```
*/
module.exports = wrap
var re = {
nonWhitespaceCharsOrNewLine: /[^\s-]+?-\b|\S+|\r\n?|\n/g,
singleNewLine: /^(\r\n?|\n)$/
}
/**
@param {string} - the input text to wrap
@param [options] {object} - optional config
@param [options.width=30] {number} - the max column width in characters
@param [options.ignore] {RegExp | RegExp[]} - one or more patterns to be ignored when sizing the newly wrapped lines. For example `ignore: /\u001b.*?m/g` will ignore unprintable ansi escape sequences.
@param [options.break] {boolean} - if true, words exceeding the specified `width` will be forcefully broken
@param [options.eol=os.EOL] {string} - the desired new line character to use, defaults to [os.EOL](https://nodejs.org/api/os.html#os_os_eol).
@return {string}
@alias module:wordwrapjs
*/
function wrap (text, options) {
options = defaultOptions(options)
text = validateInput(text)
var lines = wrap.lines(text, options)
return lines.join(options.eol)
}
/**
returns the wrapped output as an array of lines, rather than a single string
@param {string} - the input text to wrap
@param [options] {object} - same options as {@link module:wordwrapjs|wrap}
@return {Array}
@example
> bars = "I'm rapping. I'm rapping. I'm rap rap rapping. I'm rap rap rap rap rappity rapping."
> wrap.lines(bars)
[ "I'm rapping. I'm rapping. I'm",
"rap rap rapping. I'm rap rap",
"rap rap rappity rapping." ]
*/
wrap.lines = function (text, options) {
options = defaultOptions(options)
text = validateInput(text)
var words = wrap.getWords(text)
var lineLength = 0
var lines = []
var line = ''
if (options.break) {
var broken = []
words.forEach(function (word) {
var wordLength = options.ignore
? replaceIgnored(word, options.ignore).length
: word.length
if (wordLength > options.width) {
var letters = word.split('')
var section
while ((section = letters.splice(0, options.width)).length) {
broken.push(section.join(''))
}
} else {
broken.push(word)
}
})
words = broken
}
/* for each word, either extend the current `line` or create a new one */
words.forEach(function (word) {
if (re.singleNewLine.test(word)) {
lines.push(line || '')
line = ''
lineLength = 0
} else {
var wordLength = options.ignore
? replaceIgnored(word, options.ignore).length
: word.length
var offset
if (lineLength > options.width) {
offset = 0
} else {
if (/-$/.test(line)) {
offset = 0
} else {
offset = line ? 1 : 0
}
}
lineLength += wordLength + offset
if (lineLength > options.width) {
/* Can't fit word on line, cache line and create new one */
if (line) lines.push(line)
line = word
lineLength = wordLength
} else {
if (/-$/.test(line)) {
line += word
} else {
line += (line ? ' ' : '') + word
}
}
}
})
if (line) lines.push(line)
return lines
}
/**
* Returns true if the input text is wrappable
* @param {string} - input text
* @return {boolean}
*/
wrap.isWrappable = function(text) {
if (t.isDefined(text)) {
text = String(text)
var matches = text.match(re.nonWhitespaceCharsOrNewLine)
return matches ? matches.length > 1 : false
}
}
/**
* Splits the input text returning an array of words
* @param {string} - input text
* @returns {string[]}
*/
wrap.getWords = function(text) {
return text.match(re.nonWhitespaceCharsOrNewLine) || []
}
function replaceIgnored (string, ignore) {
arrayify(ignore).forEach(function (pattern) {
string = string.replace(pattern, '')
})
return string
}
function defaultOptions (options) {
options = options || {}
options.width = options.width || 30
options.eol = options.eol || os.EOL
return options
}
function validateInput (input) {
if (t.isString(input)) {
return input
} else if (!t.isDefined(input)) {
return ''
} else {
return String(input)
}
}
'use strict'
var test = require('test-runner')
var wrap = require('../')
var a = require('core-assert')
test('non-string input', function () {
a.strictEqual(wrap(undefined), '')
a.strictEqual(wrap(function () {}), 'function () {}')
a.strictEqual(wrap({}), '[object Object]')
a.strictEqual(wrap(null), 'null')
a.strictEqual(wrap(true), 'true')
a.strictEqual(wrap(0), '0')
a.strictEqual(wrap(NaN), 'NaN')
a.strictEqual(wrap(Infinity), 'Infinity')
})
'use strict'
var test = require('test-runner')
var wrap = require('../')
var a = require('core-assert')
var bars = "I'm rapping. I'm rapping. I'm rap rap rapping. I'm rap rap rap rap rappity rapping."
test('simple', function () {
a.strictEqual(
wrap(bars),
"I'm rapping. I'm rapping. I'm\nrap rap rapping. I'm rap rap\nrap rap rappity rapping."
)
})
test('width', function () {
a.strictEqual(
wrap(bars, { width: 3 }),
"I'm\nrapping.\nI'm\nrapping.\nI'm\nrap\nrap\nrapping.\nI'm\nrap\nrap\nrap\nrap\nrappity\nrapping."
)
})
test('ignore', function () {
a.strictEqual(
wrap(bars, { ignore: "I'm" }),
"I'm rapping. I'm rapping. I'm rap rap\nrapping. I'm rap rap rap rap\nrappity rapping."
)
})
test('wrap.lines', function () {
a.deepEqual(
wrap.lines(bars),
[ "I'm rapping. I'm rapping. I'm",
"rap rap rapping. I'm rap rap",
'rap rap rappity rapping.' ]
)
})
test('wrap.lines, width', function () {
a.deepEqual(
wrap.lines(bars, { width: 3 }),
[ "I'm",
'rapping.',
"I'm",
'rapping.',
"I'm",
'rap',
'rap',
'rapping.',
"I'm",
'rap',
'rap',
'rap',
'rap',
'rappity',
'rapping.' ]
)
})
test('wrap.lines, width smaller than content width', function () {
a.deepEqual(
wrap.lines('4444', { width: 3 }),
[ '4444' ]
)
a.deepEqual(
wrap.lines('onetwothreefour fivesixseveneight', { width: 7 }),
[ 'onetwothreefour', 'fivesixseveneight' ]
)
})
test('wrap.lines, break', function () {
a.deepEqual(
wrap.lines('onetwothreefour', { width: 7, break: true }),
[ 'onetwot', 'hreefou', 'r' ]
)
a.deepEqual(
wrap.lines('\u001b[4m--------\u001b[0m', { width: 10, break: true, ignore: /\u001b.*?m/g }),
[ '\u001b[4m--------\u001b[0m' ]
)
a.deepEqual(
wrap.lines(
'onetwothreefour fivesixseveneight',
{ width: 7, break: true }
),
[ 'onetwot', 'hreefou', 'r', 'fivesix', 'sevenei', 'ght' ]
)
})
test('wrap.lines(text): respect existing linebreaks', function () {
a.deepEqual(
wrap.lines('one\ntwo three four', { width: 8 }),
[ 'one', 'two', 'three', 'four' ]
)
a.deepEqual(
wrap.lines('one \n \n two three four', { width: 8 }),
[ 'one', '', 'two', 'three', 'four' ]
)
a.deepEqual(
wrap.lines('one\rtwo three four', { width: 8 }),
[ 'one', 'two', 'three', 'four' ]
)
a.deepEqual(
wrap.lines('one\r\ntwo three four', { width: 8 }),
[ 'one', 'two', 'three', 'four' ]
)
})
test('wrap.lines(text): multilingual', function () {
a.deepEqual(
wrap.lines('Può parlare più lentamente?', { width: 10 }),
[ 'Può', 'parlare', 'più', 'lentamente?' ]
)
a.deepEqual(
wrap.lines('один два три', { width: 4 }),
[ 'один', 'два', 'три' ]
)
})
test('wrap hyphenated words', function () {
a.deepEqual(
wrap.lines('ones-and-twos', { width: 5 }),
[ 'ones-', 'and-', 'twos' ]
)
a.deepEqual(
wrap.lines('ones-and-twos', { width: 10 }),
[ 'ones-and-', 'twos' ]
)
a.deepEqual(
wrap.lines('--------', { width: 5 }),
[ '--------' ]
)
a.deepEqual(
wrap.lines('--one --fifteen', { width: 5 }),
[ '--one', '--fifteen' ]
)
a.deepEqual(
wrap.lines('one-two', { width: 10 }),
[ 'one-two' ]
)
a.deepEqual(
wrap.lines('ansi-escape-sequences', { width: 22 }),
[ 'ansi-escape-sequences' ]
)
})
test('isWrappable(input)', function(t){
a.strictEqual(wrap.isWrappable('one two'), true)
a.strictEqual(wrap.isWrappable('one-two'), true)
a.strictEqual(wrap.isWrappable('one\ntwo'), true)
})