UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

91 lines (90 loc) 3.01 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.truncate = void 0; const baseToString_1 = __importDefault(require("./.internal/baseToString")); const castSlice_1 = __importDefault(require("./.internal/castSlice")); const hasUnicode_1 = __importDefault(require("./.internal/hasUnicode")); const isObject_1 = __importDefault(require("./isObject")); const isRegExp_1 = __importDefault(require("./isRegExp")); const stringSize_1 = __importDefault(require("./.internal/stringSize")); const stringToArray_1 = __importDefault(require("./.internal/stringToArray")); const toString_1 = __importDefault(require("./toString")); /** * @ignore * @private * @internal */ const DEFAULT_TRUNC_LENGTH = 30; /** * @ignore * @private * @internal */ const DEFAULT_TRUNC_OMISSION = "..."; /** * @ignore * @private * @internal */ const reFlags = /\w*$/; function truncate(str, options) { let separator; let length = DEFAULT_TRUNC_LENGTH; let omission = DEFAULT_TRUNC_OMISSION; if ((0, isObject_1.default)(options)) { separator = "separator" in options ? options.separator : separator; length = "length" in options ? options.length : length; omission = "omission" in options ? (0, baseToString_1.default)(options.omission) : omission; } str = (0, toString_1.default)(str); let strSymbols; let strLength = str.length; if ((0, hasUnicode_1.default)(str)) { strSymbols = (0, stringToArray_1.default)(str); strLength = strSymbols.length; } if (length >= strLength) { return str; } let end = length - (0, stringSize_1.default)(omission); if (end < 1) { return omission; } let result = strSymbols ? (0, castSlice_1.default)(strSymbols, 0, end).join("") : str.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if ((0, isRegExp_1.default)(separator)) { if (str.slice(end).search(separator)) { let match; let newEnd; const substring = result; if (!separator.global) { // @ts-ignore separator = RegExp(separator.source, `${reFlags.exec(separator) || ""}g`); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (str.indexOf((0, baseToString_1.default)(separator), end) != end) { const index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } exports.truncate = truncate; exports.default = truncate;