isEAN.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = isEAN;
  6. var _assertString = _interopRequireDefault(require("./util/assertString"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8. /**
  9. * The most commonly used EAN standard is
  10. * the thirteen-digit EAN-13, while the
  11. * less commonly used 8-digit EAN-8 barcode was
  12. * introduced for use on small packages.
  13. * Also EAN/UCC-14 is used for Grouping of individual
  14. * trade items above unit level(Intermediate, Carton or Pallet).
  15. * For more info about EAN-14 checkout: https://www.gtin.info/itf-14-barcodes/
  16. * EAN consists of:
  17. * GS1 prefix, manufacturer code, product code and check digit
  18. * Reference: https://en.wikipedia.org/wiki/International_Article_Number
  19. * Reference: https://www.gtin.info/
  20. */
  21. /**
  22. * Define EAN Lenghts; 8 for EAN-8; 13 for EAN-13; 14 for EAN-14
  23. * and Regular Expression for valid EANs (EAN-8, EAN-13, EAN-14),
  24. * with exact numberic matching of 8 or 13 or 14 digits [0-9]
  25. */
  26. var LENGTH_EAN_8 = 8;
  27. var LENGTH_EAN_14 = 14;
  28. var validEanRegex = /^(\d{8}|\d{13}|\d{14})$/;
  29. /**
  30. * Get position weight given:
  31. * EAN length and digit index/position
  32. *
  33. * @param {number} length
  34. * @param {number} index
  35. * @return {number}
  36. */
  37. function getPositionWeightThroughLengthAndIndex(length, index) {
  38. if (length === LENGTH_EAN_8 || length === LENGTH_EAN_14) {
  39. return index % 2 === 0 ? 3 : 1;
  40. }
  41. return index % 2 === 0 ? 1 : 3;
  42. }
  43. /**
  44. * Calculate EAN Check Digit
  45. * Reference: https://en.wikipedia.org/wiki/International_Article_Number#Calculation_of_checksum_digit
  46. *
  47. * @param {string} ean
  48. * @return {number}
  49. */
  50. function calculateCheckDigit(ean) {
  51. var checksum = ean.slice(0, -1).split('').map(function (char, index) {
  52. return Number(char) * getPositionWeightThroughLengthAndIndex(ean.length, index);
  53. }).reduce(function (acc, partialSum) {
  54. return acc + partialSum;
  55. }, 0);
  56. var remainder = 10 - checksum % 10;
  57. return remainder < 10 ? remainder : 0;
  58. }
  59. /**
  60. * Check if string is valid EAN:
  61. * Matches EAN-8/EAN-13/EAN-14 regex
  62. * Has valid check digit.
  63. *
  64. * @param {string} str
  65. * @return {boolean}
  66. */
  67. function isEAN(str) {
  68. (0, _assertString.default)(str);
  69. var actualCheckDigit = Number(str.slice(-1));
  70. return validEanRegex.test(str) && actualCheckDigit === calculateCheckDigit(str);
  71. }
  72. module.exports = exports.default;
  73. module.exports.default = exports.default;