123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- export function trimSlug(slug: string, maxLength: number = 20) {
-
- if (slug.length <= maxLength) {
- return slug;
- }
-
- const words: string[] = slug.split('-');
-
-
- if (words.length === 1) {
- return `${slug.slice(0, maxLength - 1)}\u2026`;
- }
-
- function getLength(arr: string[]): number {
- return arr.reduce((acc, cur) => acc + cur.length + 1, 0) - 1;
- }
-
-
- while (getLength(words) > maxLength && words.length > 2) {
- words.splice(Math.floor(words.length / 2 - 0.5), 1);
- }
-
-
- if (getLength(words) <= maxLength) {
- const divider = Math.floor(words.length / 2);
- return `${words.slice(0, divider).join('-')}\u2026${words.slice(divider).join('-')}`;
- }
-
-
- const debt = getLength(words) - maxLength;
- const toTrimFromLeftWord = Math.ceil(debt / 2);
- const leftWordLength = Math.max(words[0].length - toTrimFromLeftWord, 3);
- const leftWord = words[0].slice(0, leftWordLength);
- const rightWordLength = maxLength - leftWord.length;
- const rightWord = words[1].slice(-rightWordLength);
- return `${leftWord}\u2026${rightWord}`;
- }
|