-
Notifications
You must be signed in to change notification settings - Fork 0
/
issn.js
72 lines (59 loc) · 1.89 KB
/
issn.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
!function (root) {
var issn = function () {
'use strict';
var issnPattern = '^(\\d{4})-?(\\d{3})([\\dX])$';
var isIssnStrict = new RegExp(issnPattern);
var isIssnLax = new RegExp(issnPattern, 'i');
function validate(issn) {
var matches = text(issn).match(isIssnStrict);
if (!matches) {
return false;
}
var actualCheckDigit = matches[3];
var expectedCheckDigit = calculateCheckDigitFor(matches[1] + matches[2]);
return expectedCheckDigit === actualCheckDigit;
}
validate.format = function format(issn) {
var matches = text(issn).match(isIssnLax);
return matches
? matches[1] + '-' + matches[2] + matches[3].toUpperCase()
: undefined;
};
var isDigitsForChecksum = new RegExp('^(\\d{7})$');
validate.calculateCheckDigit = function calculateCheckDigit(digits) {
if (!isString(digits)) {
throw new Error('Digits must be a string of 7 numeric characters.');
}
if (!digits.match(isDigitsForChecksum)) {
throw new Error('Digits are malformed; expecting 7 numeric characters.');
}
return calculateCheckDigitFor(digits);
};
function calculateCheckDigitFor(digits) {
var result = digits.split('')
.reverse()
.reduce(function (sum, value, index) {
return sum + (value * (index + 2));
}, 0) % 11;
var checkDigit = (result === 0) ? 0 : 11 - result;
if (checkDigit === 10) {
checkDigit = 'X';
}
return checkDigit.toString();
}
function text(o) {
return isString(o) ? o : '';
}
function isString(o) {
return typeof o === 'string';
}
return validate;
}();
if (typeof exports !== 'undefined') {
if (module && typeof module.exports !== 'undefined') {
module.exports = issn;
}
} else {
root.issn = issn;
}
}(this);