-
-
Save mkxml/8810246 to your computer and use it in GitHub Desktop.
| /* | |
| 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)); | |
| }; |
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.
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
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)?