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