Skip to content

Commit

Permalink
closes #10
Browse files Browse the repository at this point in the history
also closes #15
  • Loading branch information
jonschlinkert committed Dec 29, 2016
1 parent f7b9f20 commit c1af9fc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 17 deletions.
33 changes: 17 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*
* Adapted from http://james.padolsey.com/javascript/wordwrap-for-javascript/
* @attribution
* Adapted from http://james.padolsey.com/javascript/wordwrap-for-javascript/
*/

var spaceMatch = '[\\s\u200B]';
var nonSpaceMatch = '[^\\s\u200B]'

module.exports = function(str, options) {
options = options || {};
if (str == null) {
Expand All @@ -23,26 +20,30 @@ module.exports = function(str, options) {
: ' ';

var newline = options.newline || '\n' + indent;

function identity(str) {
return str;
};
var escape = typeof options.escape === 'function'
? options.escape
: identity;

var re = new RegExp('.{1,' + width + '}(' + spaceMatch + '+|$)|' + nonSpaceMatch + '+?(' +
spaceMatch + '+|$)', 'g');

if (options.cut) {
re = new RegExp('.{1,' + width + '}', 'g');
var regexString = '.{1,' + width + '}';
if (options.cut !== true) {
regexString += '([\\s\u200B]+|$)|[^\\s\u200B]+?([\\s\u200B]+|$)';
}

var re = new RegExp(regexString, 'g');
var lines = str.match(re) || [];
var res = indent + lines.map(escape).join(newline);
var result = indent + lines.map(function(line) {
if (line.slice(-1) === '\n') {
line = line.slice(0, line.length - 1);
}
return escape(line);
}).join(newline);

if (options.trim === true) {
res = res.replace(/[ \t]*$/gm, '');
result = result.replace(/[ \t]*$/gm, '');
}
return res;
return result;
};

function identity(str) {
return str;
}
7 changes: 6 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

/* deps: mocha */
require('mocha');
var assert = require('assert');
var wrap = require('./');

Expand Down Expand Up @@ -38,6 +38,11 @@ describe('wrap', function () {
assert.equal(wrap('\r\n', {indent: '\r\n', width: 18}), '\r\n');
});

it('should handle newlines that occur at the same position as `options.width`', function () {
assert.equal(wrap('asdfg\nqwert', {width:5}), ' asdfg\n qwert');
assert.equal(wrap('aaaaaa\nbbbbbb\ncccccc', {width:6}), ' aaaaaa\n bbbbbb\n cccccc');
});

it('should handle strings that break where there are multiple spaces', function() {
assert.equal(wrap('foo foo. bar', {width:8}), ' foo foo. \n bar');
assert.equal(wrap('foo foo. bar', {width:8, trim: true}), ' foo foo.\n bar');
Expand Down

0 comments on commit c1af9fc

Please sign in to comment.