skip to Main Content

How to implement the check digit algorithm specified in ISO 6346 Freight containers — Coding, identification and marking?

2

Answers


  1. Chosen as BEST ANSWER

    Implementation in JavaScript:

    function checkCscDigit(csc) {
        csc = csc.toUpperCase().replace(/[^A-Z0-9]+/g, '');
        if (csc.length < 10) return [ null, null ];
    
        // Retreive the check digit from the string (11th character.)
        let check = (csc.length == 11 && !isNaN(csc[10])) ? parseInt(csc[10]) : null;
    
        // Calculate check digit.
        var sum = 0;
        for (let i = 0; i < 10; i++) {
    
            // Convert letters to numbers.
            let n = isNaN(csc[i]) ? csc.charCodeAt(i) - 55 : parseInt(csc[i]);
    
            if (n) {
              // Digits 11, 22, 33 are omitted.
                n += Math.floor((n-1) / 10);
    
              // Sum of all digits multiplied by weighting.
              sum += n * Math.pow(2, i);
            }
        }
    
        // Modulus of 11, and convert 10 to 0.
        let calculation = sum % 11 % 10;
    
        return [ check, calculation ];
    }
    

    Usage:

    let [check, calculation] = checkCscDigit('ABCD 123456 [0]');
    
    if (calculation !== null) {
        console.log(check, calculation)
        if (check === calculation) {
            console.log('Valid!');
        }
    }
    
    

    Here, check is the 11th character extracted from the string, which is the check digit. calculation is the check digit calculated from the first 10 characters in the string. If these two match, then the string is valid.

    JSFiddle


  2. Alternatively, using map and reduce.

        let calculation = Array.from(csc.slice(0, 10))
          .map(c => isNaN(c) ? c.charCodeAt(0) - 55 : parseInt(c)) // To digit.
          .map(d => d + Math.floor(Math.max(0, d-1) / 10)) // Omit multiples of 11.
          .map((d, i) => d * Math.pow(2, i)) // Weighting.
          .reduce((a, b) => a + b) // Summation.
          % 11 // Modulus of 11.
          % 10; // Convert 10 to 0.
    

    (Where csc is a valid 11 digit string 'ABCD1234560'.)

    JSFiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search