Last active
April 20, 2021 13:27
-
-
Save mkxml/8810246 to your computer and use it in GitHub Desktop.
Check Digit JavaScript function for modulo 11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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)); | |
| }; |
Author
K???
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
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.