music-codes
Version:
Small library for music codes (ISRC, ISWC, UPC)
27 lines • 944 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLuhnCheckDigit = getLuhnCheckDigit;
exports.raise = raise;
const errors_js_1 = require("./errors.js");
/**
* Naive implementation of Luhn algorithm for GTIN check digit
* Does not check for valid code length
* @see https://www.gs1.org/services/how-calculate-check-digit-manually
* @see https://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#JavaScript
*/
function getLuhnCheckDigit(code) {
const str = String(code);
if (!/^\d+$/.test(str))
throw new errors_js_1.CodeValidationError(`Invalid code: ${str}`);
const cd = str
.split('')
.reverse()
.reduce((acc, v, idx) => {
return acc + (idx % 2 ? 1 : 3) * Number.parseInt(v);
}, 0) % 10;
return cd === 0 ? 0 : 10 - cd;
}
function raise(message) {
throw new errors_js_1.InvalidStateError(message);
}
//# sourceMappingURL=utils.js.map