1 |
|
2 |
|
3 |
|
4 | export class Slugger {
|
5 | constructor() {
|
6 | this.seen = {};
|
7 | }
|
8 |
|
9 | serialize(value) {
|
10 | return value
|
11 | .toLowerCase()
|
12 | .trim()
|
13 |
|
14 | .replace(/<[!\/a-z].*?>/ig, '')
|
15 |
|
16 | .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '')
|
17 | .replace(/\s/g, '-');
|
18 | }
|
19 |
|
20 | |
21 |
|
22 |
|
23 | getNextSafeSlug(originalSlug, isDryRun) {
|
24 | let slug = originalSlug;
|
25 | let occurenceAccumulator = 0;
|
26 | if (this.seen.hasOwnProperty(slug)) {
|
27 | occurenceAccumulator = this.seen[originalSlug];
|
28 | do {
|
29 | occurenceAccumulator++;
|
30 | slug = originalSlug + '-' + occurenceAccumulator;
|
31 | } while (this.seen.hasOwnProperty(slug));
|
32 | }
|
33 | if (!isDryRun) {
|
34 | this.seen[originalSlug] = occurenceAccumulator;
|
35 | this.seen[slug] = 0;
|
36 | }
|
37 | return slug;
|
38 | }
|
39 |
|
40 | |
41 |
|
42 |
|
43 |
|
44 |
|
45 | slug(value, options = {}) {
|
46 | const slug = this.serialize(value);
|
47 | return this.getNextSafeSlug(slug, options.dryrun);
|
48 | }
|
49 | }
|