Skip to content

Instantly share code, notes, and snippets.

@mkxml
Last active April 20, 2021 13:27
Show Gist options
  • Select an option

  • Save mkxml/8810246 to your computer and use it in GitHub Desktop.

Select an option

Save mkxml/8810246 to your computer and use it in GitHub Desktop.
Check Digit JavaScript function for modulo 11
/*
Check digit using modulo 11
Arguments:
- n is your given number to test the check digit
- x is an optional argument that is used to determine the check digit
used in case of the rest of the division is less than 2. Defaults to 0.
Returns an integer, the checkDigit for the given number.
*/
var checkDigit11 = function(n, x) {
var l = n.length, i = 0, j = (l%8), v = 0;
for(i = 0, l = l-1; i < l; i++) {
v += parseInt(n[i], 10) * j;
j = (j == 2) ? 9 : --j;
}
return v = (v%11 < 2) ? (x || 0) : (11 - (v%11));
};
@kennymac
Copy link

Apologies if I misunderstand the algorithm you're using, but i < (L-1) looks odd, shouldn't you iterate through the entire array, using (i < L)?

@mkxml
Copy link
Author

mkxml commented Aug 9, 2016

Sorry for the delay, I didn't see your comment. For its purpose, the code is correct because the function is testing the check digit. So it's expecting a number with the check digit included. If you provide a valid modulo 11 number, the last digit should be equal to the output of the function.

You could change the function and alter the code the way you described, then the function will generate the check digit from a number without one.

@migb
Copy link

migb commented Mar 27, 2018

K???

@Tofandel
Copy link

Tofandel commented Apr 20, 2021

Why are you returning the value of an assignment ? v = (v%11 < 2) ? ... this is bad practice and makes the code uselessly confusing here

Function is also not working correctly because j goes negative for strings that are 8 chars or more, the function also doesn't actually return the check of the last digit, it only returns the expected one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment