all files / dist-modules/ index.js

100% Statements 16/16
100% Branches 12/12
100% Functions 2/2
100% Lines 16/16
1 branch Ignored     
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 29 30 31 32 33 34                            12×        
'use strict';
 
module.exports = function (str, maxChars, options) {
  var _optionsDefault = {
    wordBoundary: true,
    chars: [' ', '-'],
    endSymbols: '...'
  };
  var charRegx = /\s* \s*|\s*-\s*/;
  var words = str.split(charRegx);
  var retStr = '';
 
  options = Object.assign(_optionsDefault, options);
 
  function appendEndSymbols(strlen, maxChars, endSymbols) /* istanbul ignore next */{
    return strlen > maxChars ? endSymbols : '';
  }
 
  if (!maxChars || str.length <= maxChars) {
    return str;
  }
 
  if (!options.wordBoundary) {
    return str.substring(0, maxChars) + appendEndSymbols(str.length, maxChars, options.endSymbols);
  }
 
  for (var i = 0; i < words.length; i++) {
    if ((retStr + ' ' + words[i]).length > maxChars) {
      return str.substring(0, retStr.length) + appendEndSymbols(str.length, retStr.length, options.endSymbols);
    } else {
      retStr = i === 0 ? words[0] : retStr + (' ' + words[i]);
    }
  }
};