Source

string/truncate.js

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var isFullWidthChar_1 = __importDefault(require("./isFullWidthChar"));
/**
 * Truncate string with handling of full width characters (e.g. Chinese/Japanese)
 *
 * @param {string} str
 * @param {Object} options
 *
 * @returns {string}
 * @category string
 * @module truncate
 */
var truncate = function (str, options) {
    if (str === void 0) { str = ''; }
    var maxLength = options.length, omission = options.omission;
    var length = 0;
    var charIndex = 0;
    var truncatedStr = '';
    do {
        var char = (str || '')[charIndex] || '';
        if ((0, isFullWidthChar_1.default)(char)) {
            if (length + 2 > maxLength)
                break;
            length += 2;
        }
        else {
            length += 1;
        }
        truncatedStr += char;
        charIndex++;
    } while (length < maxLength);
    var isTruncated = (str || '').length !== truncatedStr.length;
    return "".concat(truncatedStr).concat(isTruncated ? omission || '...' : '');
};
exports.default = truncate;