source: node_modules/es-toolkit/dist/compat/string/truncate.mjs

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

Added visualizations

  • Property mode set to 100644
File size: 1.6 KB
Line 
1import { isObject } from '../predicate/isObject.mjs';
2
3const regexMultiByte = /[\u200d\ud800-\udfff\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff\ufe0e\ufe0f]/;
4function truncate(string, options) {
5 string = string != null ? `${string}` : '';
6 let length = 30;
7 let omission = '...';
8 if (isObject(options)) {
9 length = parseLength(options.length);
10 omission = 'omission' in options ? `${options.omission}` : '...';
11 }
12 let i = string.length;
13 const lengthOmission = Array.from(omission).length;
14 const lengthBase = Math.max(length - lengthOmission, 0);
15 let strArray = undefined;
16 const unicode = regexMultiByte.test(string);
17 if (unicode) {
18 strArray = Array.from(string);
19 i = strArray.length;
20 }
21 if (length >= i) {
22 return string;
23 }
24 if (i <= lengthOmission) {
25 return omission;
26 }
27 let base = strArray === undefined ? string.slice(0, lengthBase) : strArray?.slice(0, lengthBase).join('');
28 const separator = options?.separator;
29 if (!separator) {
30 base += omission;
31 return base;
32 }
33 const search = separator instanceof RegExp ? separator.source : separator;
34 const flags = 'u' + (separator instanceof RegExp ? separator.flags.replace('u', '') : '');
35 const withoutSeparator = new RegExp(`(?<result>.*(?:(?!${search}).))(?:${search})`, flags).exec(base);
36 return (!withoutSeparator?.groups ? base : withoutSeparator.groups.result) + omission;
37}
38function parseLength(length) {
39 if (length == null) {
40 return 30;
41 }
42 if (length <= 0) {
43 return 0;
44 }
45 return length;
46}
47
48export { truncate };
Note: See TracBrowser for help on using the repository browser.