forked from betagouv/nir_validate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (38 loc) · 1.06 KB
/
index.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
function handleSpecialCodes(nirpp) {
if (nirpp.indexOf('A') !== -1) {
return {
withoutLetters: nirpp.replace('A', '0'),
offset: 1000000,
};
}
if (nirpp.indexOf('B') !== -1) {
return {
withoutLetters: nirpp.replace('B', '0'),
offset: 2000000,
};
}
return {
withoutLetters: nirpp,
offset: 0,
};
}
function parse(nirpp) {
const { withoutLetters, offset } = handleSpecialCodes(nirpp);
return parseInt(withoutLetters, 10) - offset;
}
function generateControlKey(nirpp) {
return 97 - (parse(nirpp) % 97);
}
function clean(nirpp) {
return nirpp.toUpperCase().replace(/\s+/g, '');
}
function validCq(input, options = {}) {
if (typeof input !== 'string') throw new TypeError('Input should be a string');
const { shouldClean } = options;
const cleanedInput = shouldClean === false ? input : clean(input);
const key = cleanedInput.slice(-2);
const withoutKey = cleanedInput.slice(0, -2);
const computedKey = generateControlKey(withoutKey);
return computedKey == key;
}
module.exports = { validate: validCq };