'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var isNum = _interopDefault(require('./isNum'));
var consts = require('./consts');

/**
 * 裁切字符串，超出部分以超出符代替
 * @param {*} string 原字符串
 * @param {*} length 限定长度
 * @param {*} omission  超出符，默认为：...
 *
 * cutString('测试字符串裁切函数，过长溢出显示省略', 20);                     // => '测试字符串裁切函数，...'
 * cutString('Test cutString function, overflow display omission', 20); // => 'Test cutString fun...'
 */
function cutString(string, length, omission) {
  if (omission === undefined) omission = '...';
  if (!isNum(length)) return string;
  var tmpChar;
  var tmpStr = '';
  var count = 0;
  var hasRest = false;
  var i = -1;

  while (++i < string.length) {
    if (count >= length) {
      hasRest = true;
      break;
    }

    tmpChar = string.substr(i, 1);
    tmpStr += tmpChar;
    count += consts.RE_DB_CHAR.test(tmpChar) ? 2 : 1;
  }

  return tmpStr + (hasRest ? omission : '');
}

module.exports = cutString;
