checksums.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Various checksum calculations
  3. *
  4. */
  5. /*
  6. * weight3odd10
  7. *
  8. * Calculates the checksum, odds have a weight of 3, then MOD 10.
  9. *
  10. * @param String seq - Sequence of int to find the checksum of
  11. * @param Number - Checksum
  12. *
  13. * Used by:
  14. * - UPC-A
  15. * - UPC-E
  16. * - EAN8
  17. */
  18. function weight3odd10(seq) {
  19. var dInt, ret = 0;
  20. // Using a 1-index for this simply because we can match the position in the
  21. // sequence with our counter variable.
  22. for (var i = 1; i <= seq.length; i++) {
  23. dInt = parseInt(seq[i - 1]);
  24. ret += (i & 1) ? dInt * 3 : dInt;
  25. }
  26. return (10 - ret % 10) % 10;
  27. }
  28. /*
  29. * weight3even10
  30. *
  31. * Calculates the checksum, evens have a weight of 3, then MOD 10.
  32. * What's funny about this is that we can simply prepend a 0 to the sequence
  33. * to shift the odds to the evens then pass it weight3odd().
  34. *
  35. * @param String seq - Sequence of ints to find the checksum of
  36. * @param Number - Checksum
  37. *
  38. * Used by:
  39. * - EAN13
  40. */
  41. function weight3even10(seq) {
  42. return weight3odd10('0' + seq);
  43. }
  44. /*
  45. * Our exports
  46. */
  47. module.exports.weight3odd10 = weight3odd10;
  48. module.exports.weight3even10 = weight3even10;