1 import { camelToSnakeCase } from "./camel-to-snake-case"
2 import { simpleHash } from "./simple-hash"
3
4 export function compressName(name: string, limit = 58) {
5 if (name.length <= limit) {
6 return name.toLowerCase()
7 }
8
9 const hash = simpleHash(name).toLowerCase()
10 const hashLength = hash.length
11
12 // Remove consecutive duplicates
13 const parts = name.toLowerCase().split("_")
14 const deduplicatedParts: string[] = []
15
16 for (let i = 0; i < parts.length; i++) {
17 if (i === 0 || parts[i] !== parts[i - 1]) {
18 deduplicatedParts.push(parts[i])
19 }
20 }
21
22 let result = deduplicatedParts.join("_")
23
24 // If still greater than the limit, truncate each part to 4 characters
25 if (result.length > limit) {
26 const allParts = camelToSnakeCase(name).split("_")
27 result = allParts.map((part) => part.substring(0, 4)).join("_")
28 }
29
30 name = result
31 const nameLength = name.length
32 const diff = nameLength + hashLength - limit
33
34 if (diff > 0) {
35 return name.slice(0, nameLength - diff) + hash
36 }
37
38 return (name + hash).toLowerCase()
39 }