27 lines
818 B
TypeScript
27 lines
818 B
TypeScript
// Custom Slugger class to replace the one from 'marked' due to import issues.
|
|
// This mimics the behavior of creating unique slugs for duplicate headings.
|
|
export class CustomSlugger {
|
|
private seen: { [key: string]: number } = {};
|
|
slug(value: any) {
|
|
// Accept any type to be robust
|
|
// Coerce value to a string to prevent errors if it's not a string type, like in some edge cases with marked's parser.
|
|
const stringValue = String(value || '');
|
|
|
|
let slug = stringValue
|
|
.toLowerCase()
|
|
.trim()
|
|
.replace(/[\s_]+/g, '-')
|
|
.replace(/[^\w-]+/g, '')
|
|
.replace(/--+/g, '-');
|
|
|
|
const seenCount = this.seen[slug];
|
|
if (seenCount) {
|
|
this.seen[slug] = seenCount + 1;
|
|
slug = `${slug}-${seenCount}`;
|
|
} else {
|
|
this.seen[slug] = 1;
|
|
}
|
|
return slug;
|
|
}
|
|
}
|