index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Encoding documentation:
  2. // https://en.wikipedia.org/wiki/Code_39#Encoding
  3. import Barcode from "../Barcode.js";
  4. class CODE39 extends Barcode {
  5. constructor(data, options){
  6. data = data.toUpperCase();
  7. // Calculate mod43 checksum if enabled
  8. if(options.mod43){
  9. data += getCharacter(mod43checksum(data));
  10. }
  11. super(data, options);
  12. }
  13. encode(){
  14. // First character is always a *
  15. var result = getEncoding("*");
  16. // Take every character and add the binary representation to the result
  17. for(let i = 0; i < this.data.length; i++){
  18. result += getEncoding(this.data[i]) + "0";
  19. }
  20. // Last character is always a *
  21. result += getEncoding("*");
  22. return {
  23. data: result,
  24. text: this.text
  25. };
  26. }
  27. valid(){
  28. return this.data.search(/^[0-9A-Z\-\.\ \$\/\+\%]+$/) !== -1;
  29. }
  30. }
  31. // All characters. The position in the array is the (checksum) value
  32. var characters = [
  33. "0", "1", "2", "3",
  34. "4", "5", "6", "7",
  35. "8", "9", "A", "B",
  36. "C", "D", "E", "F",
  37. "G", "H", "I", "J",
  38. "K", "L", "M", "N",
  39. "O", "P", "Q", "R",
  40. "S", "T", "U", "V",
  41. "W", "X", "Y", "Z",
  42. "-", ".", " ", "$",
  43. "/", "+", "%", "*"
  44. ];
  45. // The decimal representation of the characters, is converted to the
  46. // corresponding binary with the getEncoding function
  47. var encodings = [
  48. 20957, 29783, 23639, 30485,
  49. 20951, 29813, 23669, 20855,
  50. 29789, 23645, 29975, 23831,
  51. 30533, 22295, 30149, 24005,
  52. 21623, 29981, 23837, 22301,
  53. 30023, 23879, 30545, 22343,
  54. 30161, 24017, 21959, 30065,
  55. 23921, 22385, 29015, 18263,
  56. 29141, 17879, 29045, 18293,
  57. 17783, 29021, 18269, 17477,
  58. 17489, 17681, 20753, 35770
  59. ];
  60. // Get the binary representation of a character by converting the encodings
  61. // from decimal to binary
  62. function getEncoding(character){
  63. return getBinary(characterValue(character));
  64. }
  65. function getBinary(characterValue){
  66. return encodings[characterValue].toString(2);
  67. }
  68. function getCharacter(characterValue){
  69. return characters[characterValue];
  70. }
  71. function characterValue(character){
  72. return characters.indexOf(character);
  73. }
  74. function mod43checksum(data){
  75. var checksum = 0;
  76. for(let i = 0; i < data.length; i++){
  77. checksum += characterValue(data[i]);
  78. }
  79. checksum = checksum % 43;
  80. return checksum;
  81. }
  82. export {CODE39};