EAN13.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Encoding documentation:
  2. // https://en.wikipedia.org/wiki/International_Article_Number_(EAN)#Binary_encoding_of_data_digits_into_EAN-13_barcode
  3. import { EAN13_STRUCTURE } from './constants';
  4. import EAN from './EAN';
  5. // Calculate the checksum digit
  6. // https://en.wikipedia.org/wiki/International_Article_Number_(EAN)#Calculation_of_checksum_digit
  7. const checksum = (number) => {
  8. const res = number
  9. .substr(0, 12)
  10. .split('')
  11. .map((n) => +n)
  12. .reduce((sum, a, idx) => (
  13. idx % 2 ? sum + a * 3 : sum + a
  14. ), 0);
  15. return (10 - (res % 10)) % 10;
  16. };
  17. class EAN13 extends EAN {
  18. constructor(data, options) {
  19. // Add checksum if it does not exist
  20. if (data.search(/^[0-9]{12}$/) !== -1) {
  21. data += checksum(data);
  22. }
  23. super(data, options);
  24. // Adds a last character to the end of the barcode
  25. this.lastChar = options.lastChar;
  26. }
  27. valid() {
  28. return (
  29. this.data.search(/^[0-9]{13}$/) !== -1 &&
  30. +this.data[12] === checksum(this.data)
  31. );
  32. }
  33. leftText() {
  34. return super.leftText(1, 6);
  35. }
  36. leftEncode() {
  37. const data = this.data.substr(1, 6);
  38. const structure = EAN13_STRUCTURE[this.data[0]];
  39. return super.leftEncode(data, structure);
  40. }
  41. rightText() {
  42. return super.rightText(7, 6);
  43. }
  44. rightEncode() {
  45. const data = this.data.substr(7, 6);
  46. return super.rightEncode(data, 'RRRRRR');
  47. }
  48. // The "standard" way of printing EAN13 barcodes with guard bars
  49. encodeGuarded() {
  50. const data = super.encodeGuarded();
  51. // Extend data with left digit & last character
  52. if (this.options.displayValue) {
  53. data.unshift({
  54. data: '000000000000',
  55. text: this.text.substr(0, 1),
  56. options: { textAlign: 'left', fontSize: this.fontSize }
  57. });
  58. if (this.options.lastChar) {
  59. data.push({
  60. data: '00'
  61. });
  62. data.push({
  63. data: '00000',
  64. text: this.options.lastChar,
  65. options: { fontSize: this.fontSize }
  66. });
  67. }
  68. }
  69. return data;
  70. }
  71. }
  72. export default EAN13;