| 1 | 'use strict';
|
|---|
| 2 |
|
|---|
| 3 | Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|---|
| 4 |
|
|---|
| 5 | const isObject = require('../predicate/isObject.js');
|
|---|
| 6 |
|
|---|
| 7 | const regexMultiByte = /[\u200d\ud800-\udfff\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff\ufe0e\ufe0f]/;
|
|---|
| 8 | function truncate(string, options) {
|
|---|
| 9 | string = string != null ? `${string}` : '';
|
|---|
| 10 | let length = 30;
|
|---|
| 11 | let omission = '...';
|
|---|
| 12 | if (isObject.isObject(options)) {
|
|---|
| 13 | length = parseLength(options.length);
|
|---|
| 14 | omission = 'omission' in options ? `${options.omission}` : '...';
|
|---|
| 15 | }
|
|---|
| 16 | let i = string.length;
|
|---|
| 17 | const lengthOmission = Array.from(omission).length;
|
|---|
| 18 | const lengthBase = Math.max(length - lengthOmission, 0);
|
|---|
| 19 | let strArray = undefined;
|
|---|
| 20 | const unicode = regexMultiByte.test(string);
|
|---|
| 21 | if (unicode) {
|
|---|
| 22 | strArray = Array.from(string);
|
|---|
| 23 | i = strArray.length;
|
|---|
| 24 | }
|
|---|
| 25 | if (length >= i) {
|
|---|
| 26 | return string;
|
|---|
| 27 | }
|
|---|
| 28 | if (i <= lengthOmission) {
|
|---|
| 29 | return omission;
|
|---|
| 30 | }
|
|---|
| 31 | let base = strArray === undefined ? string.slice(0, lengthBase) : strArray?.slice(0, lengthBase).join('');
|
|---|
| 32 | const separator = options?.separator;
|
|---|
| 33 | if (!separator) {
|
|---|
| 34 | base += omission;
|
|---|
| 35 | return base;
|
|---|
| 36 | }
|
|---|
| 37 | const search = separator instanceof RegExp ? separator.source : separator;
|
|---|
| 38 | const flags = 'u' + (separator instanceof RegExp ? separator.flags.replace('u', '') : '');
|
|---|
| 39 | const withoutSeparator = new RegExp(`(?<result>.*(?:(?!${search}).))(?:${search})`, flags).exec(base);
|
|---|
| 40 | return (!withoutSeparator?.groups ? base : withoutSeparator.groups.result) + omission;
|
|---|
| 41 | }
|
|---|
| 42 | function parseLength(length) {
|
|---|
| 43 | if (length == null) {
|
|---|
| 44 | return 30;
|
|---|
| 45 | }
|
|---|
| 46 | if (length <= 0) {
|
|---|
| 47 | return 0;
|
|---|
| 48 | }
|
|---|
| 49 | return length;
|
|---|
| 50 | }
|
|---|
| 51 |
|
|---|
| 52 | exports.truncate = truncate;
|
|---|