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));
};
@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