source: node_modules/es-toolkit/dist/compat/string/truncate.js@ ba17441

Last change on this file since ba17441 was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 1.7 KB
Line 
1'use strict';
2
3Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
5const isObject = require('../predicate/isObject.js');
6
7const regexMultiByte = /[\u200d\ud800-\udfff\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff\ufe0e\ufe0f]/;
8function 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}
42function parseLength(length) {
43 if (length == null) {
44 return 30;
45 }
46 if (length <= 0) {
47 return 0;
48 }
49 return length;
50}
51
52exports.truncate = truncate;
Note: See TracBrowser for help on using the repository browser.