forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslug.js
66 lines (51 loc) · 1.57 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
import limax from 'limax';
import {SLUG_LANG, SLUG_SEPARATOR} from '../../config';
/* latinizer processor */
export const limaxProcessor = (string, lang = SLUG_LANG) => limax(string, {
custom: ['$'],
separator: SLUG_SEPARATOR,
maintainCase: true,
lang
});
/* 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'
? limaxProcessor(chunk.string)
: chunk.string;
processed.length > 0 && accum.push(processed);
return accum;
}, [])
.join(SLUG_SEPARATOR);
/* session processor */
export const makeSessionSlugProcessor = (preserveUnicode = false) => {
const processor = preserveUnicode ? unicodeSafeProcessor : limaxProcessor;
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;
}
}