I want to validate the INN code. I have code snippet in Java which validates the INN code and want to port it to JavaScript to use it on my website (React):
for (int index = 0; index < lastCharacterIndex; index++) {
sum += Character.digit(characters.get(index)) * INN_MULTIPLIERS[index];
}
checkDigit = (sum % 11) % 10;
returnValue = Character.digit(characters.get(lastCharacterIndex), 10) == checkDigit;
private static final int[] INN_MULTIPLIERS = {-1, 5, 7, 9, 4, 6, 10, 5, 7};
I tried to translate it but it fails:
const validateINNCode = (innCode) => {
let sum = 0;
const INN_MULTIPLIERS = [-1, 5, 7, 9, 4, 6, 10, 5, 7];
for (let index = 0; index < innCode.length; index++) {
sum += innCode[index] * INN_MULTIPLIERS[index];
}
const checkDigit = (sum % 11) % 10;
const returnValue = innCode.length == checkDigit;
return returnValue;
};
Any ideas how to correctly port this Java code to JavaScript? Thanks.
Porting code over from Java to JavaScript is a fairly easy task.
You should probably include the full Java code. Here is what I believe it would look like:
Note: I see that characters.get
is called, so it looks like characters
is a List<Character>
. It would have been better to show how the Java code translated a String
into this List
.
import java.util.List;
public class Validator {
private static final int[] INN_MULTIPLIERS = {-1, 5, 7, 9, 4, 6, 10, 5, 7};
public static boolean isValid(List<Character> characters) {
int sum = 0;
int lastCharacterIndex = characters.size() - 1;
for (int index = 0; index < lastCharacterIndex; index++) {
sum += Character.digit(characters.get(index), 10) * INN_MULTIPLIERS[index];
}
int checkDigit = (sum % 11) % 10;
return Character.digit(characters.get(lastCharacterIndex), 10) == checkDigit;
}
public static void main(String[] args) {
// for (int i = 10000000; i < 99999999; i++) {
// String code = Integer.toString(i, 10);
// List<Character> digits = code.chars().mapToObj(e -> (char) e).toList();
// if (isValid(digits)) {
// System.out.println(i); // A valid code
// }
// }
String code = "18158984"; // Should be valid
List<Character> digits = code.chars().mapToObj(e -> (char) e).toList();
System.out.println(isValid(digits));
}
}
Here is the equivalent JavaScript code:
Character.digit
can be ported over to parseInt
==
(double equals) in Java should be ===
(triple equals) in JavaScriptconst INN_MULTIPLIERS = [-1, 5, 7, 9, 4, 6, 10, 5, 7];
function isValid(characters) {
let sum = 0;
const lastCharacterIndex = characters.length - 1;
for (let index = 0; index < lastCharacterIndex; index++) {
sum += parseInt(characters[index], 10) * INN_MULTIPLIERS[index];
}
const checkDigit = (sum % 11) % 10;
return parseInt(characters[lastCharacterIndex], 10) === checkDigit;
}
const code = "18158984"; // Should be valid
const digits = code.split('');
console.log(isValid(digits));