将 INN 代码验证从 Java 移植到 JavaScript

问题描述 投票:0回答:1

我想验证 INN 代码。我有 Java 代码片段,用于验证 INN 代码,并希望将其移植到 JavaScript 以在我的网站上使用它(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};

我尝试翻译它但失败了:

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

有什么想法可以正确地将这个 Java 代码移植到 JavaScript 吗?谢谢。

javascript java reactjs porting
1个回答
0
投票

将代码从 Java 移植到 JavaScript 是一项相当简单的任务。

您可能应该包含完整的 Java 代码。我相信它会是这样的:

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

这是等效的 JavaScript 代码:

const 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));

© www.soinside.com 2019 - 2024. All rights reserved.