forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslug.js
78 lines (61 loc) · 1.92 KB
/
slug.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import slugify from '@sindresorhus/slugify';
import {SLUG_SEPARATOR} from '../../config';
/* url-safe processor */
export const urlsafeSlugProcessor = string =>
slugify(string, {
customReplacements: [ // runs before any other transformations
['$', 'DOLLAR'], // `$destroy` & co
['-', 'DASH'], // conflicts with `separator`
],
separator: SLUG_SEPARATOR,
decamelize: false,
lowercase: false
})
.replace(/DOLLAR/g, '$')
.replace(/DASH/g, '-');
/* unicode-preserver processor */
const alphaNumRegex = /[a-zA-Z0-9]/;
const unicodeRegex = /\p{Letter}/u;
const isNonAlphaNumUnicode =
string => !alphaNumRegex.test(string) && unicodeRegex.test(string);
export const unicodeSafeProcessor = string =>
string.split('')
.reduce((accum, char, index, array) => {
const type = isNonAlphaNumUnicode(char) ? 'pass' : 'process';
if (index === 0) {
accum.current = {type, string: char};
} else if (type === accum.current.type) {
accum.current.string += char;
} else {
accum.chunks.push(accum.current);
accum.current = {type, string: char};
}
if (index === array.length - 1) {
accum.chunks.push(accum.current);
}
return accum;
}, {chunks: [], current: {type: '', string: ''}})
.chunks
.reduce((accum, chunk) => {
const processed = chunk.type === 'process'
? urlsafeSlugProcessor(chunk.string)
: chunk.string;
processed.length > 0 && accum.push(processed);
return accum;
}, [])
.join(SLUG_SEPARATOR);
/* processor */
export const makeSlugProcessor = (preserveUnicode = false) => preserveUnicode
? unicodeSafeProcessor
: urlsafeSlugProcessor;
/* session processor */
export const makeSessionSlugProcessor = (preserveUnicode = false) => {
const processor = makeSlugProcessor(preserveUnicode);
const seen = new Set();
return string => {
const slug = processor(string);
if (seen.has(slug)) throw new Error(`Duplicate slug ${slug}`);
seen.add(slug);
return slug;
};
};