The Code Behind Barcodes

4.3.1 Validate UPC

This function accepts a string value. It checks and returns true if the length of the barcode is 12.

// Validate UPC length
function isValidUPC(barcode){
  // Are all characters digits?
  [...barcode].forEach(function(digit, i){
    if(!digitExp.test(digit))
      return false;
  })
  return barcode.length == 12;
  return barcode.length == 12 &&
         calculateCheckDigit(barcode) == barcode[11];
}

4.3.2 Calculate Check Digit

calculateCheckDigit uses the formula discussed in 3.4 Check Digit Calculation to calculate and return the correct check digit. This method can check digit generation or validation. For our use case, we will only be validating the check digit.

// Calculate Check Digit
function calculateCheckDigit(barcode){
  let sum = 0;

  // Iterate barcode
  [...barcode].forEach((item, i) => {
    // Add odd digits that are not the number system digit or check digit. Multiply the result by 3
    if ((i != 0 && i != 11) && i % 2 == 0){
      sum += 3 * parseInt(item);
    }
    // Sum odd digits where digit is neither first nor last.
    else if (i != 0 && i != 11) {
      sum += parseInt(item);
    }
  });

  // result mod 10
  var result = sum % 10;

  // If result is 0, return 0. Otherwise return 10 - result
  if (result == 0){
    return 0;
  }
  else{
    return 10 - result;
  }
}

4.3.3 Processing the UPC

preprocessUPC will fetch and process the user-entered number. After fetching the value of the input, we use both validation functions on the value. Error messages will display on invalid entries.

// Process user input
function preprocessUPC(){
  // Get user value from form
  var barcode = document.getElementById('upc').value;

  // Validate UPC
  var errorBox = document.getElementById('error');
  if (!isValidUPC(barcode)){
    errorBox.innerHTML = upcError;
    errorBox.removeAttribute('hidden');
    return false;
  }
  else {
    document.getElementById('error').setAttribute('hidden', true);
  }

  // Validate check digit
  var check = calculateCheckDigit(barcode);
  // Display error if check is not equal to check digit in barcode
  if (check != barcode[11]){
    errorBox.innerHTML = checkError + check;
    errorBox.removeAttribute('hidden');
    return false;
  }
  else {
    errorBox.setAttribute('hidden', true);
  }

  // Everything checks out
  return barcode;
}

4.3.4 Filling the Background

Our first rendering function will fill the background. It is pretty straightforward. We will set the fill color to white and fill the background.

function fillBG(){
  // Fill background
  ctx.fillStyle = 'white';
  ctx.fillRect(0, 0, imageSize[0], imageSize[1]);
}