isISBN.js
1.5 KB
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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISBN;
var _assertString = _interopRequireDefault(require("./util/assertString"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/;
var isbn13Maybe = /^(?:[0-9]{13})$/;
var factor = [1, 3];
function isISBN(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
(0, _assertString.default)(str);
version = String(version);
if (!version) {
return isISBN(str, 10) || isISBN(str, 13);
}
var sanitized = str.replace(/[\s-]+/g, '');
var checksum = 0;
var i;
if (version === '10') {
if (!isbn10Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 9; i++) {
checksum += (i + 1) * sanitized.charAt(i);
}
if (sanitized.charAt(9) === 'X') {
checksum += 10 * 10;
} else {
checksum += 10 * sanitized.charAt(9);
}
if (checksum % 11 === 0) {
return !!sanitized;
}
} else if (version === '13') {
if (!isbn13Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 12; i++) {
checksum += factor[i % 2] * sanitized.charAt(i);
}
if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) {
return !!sanitized;
}
}
return false;
}
module.exports = exports.default;
module.exports.default = exports.default;