Any time you're struggling to wrap your head around large tasks like these I recommend breaking your problem down into individual parts and turning them into functions you can tackle one by one.
(任何时候,当您为解决诸如此类的大型任务而挣扎时,我建议将您的问题分解为各个部分,并将其转变为可以一一解决的功能。)
First you probably want to make sure that no number is repeated more than twice.
(首先,您可能要确保没有数字重复超过两次。)
A good way to do this would be to tally up how often each number is repeated with something like this.(做到这一点的一个好方法是计算出每个数字重复这样的频率。)
const hasValidFrequency = (string) => {
const array = string.split("")
const tallied = {}
for (const elem of array) {
tallied[elem] = (tallied[elem] || 0) + 1
}
// you might have to tweak this function slightly to make it
// return the problematic digit if necessary
return Object.values(tallied).every(frequency => frequency < 3)
}
This way you could call the function and make sure every key in here has a maximum value of 2.
(这样,您可以调用该函数并确保此处的每个键的最大值为2。)
For the next validation, you could do a for loop backwards and figure start multiplying the digits.
(对于下一个验证,您可以向后进行for循环,然后数字开始乘以数字。)
const isValidMultiple = (string) => {
let result = 0
for (let i = 9; i >= 1; i--) {
const letter = string[string.length - i]
result += Number(letter) * i
}
return result % 11 === 0
}
Now you can put these together in your handler and call it in a readable manner.
(现在,您可以将它们放到处理程序中,并以可读的方式调用它。)
if (hasValidFrequency(input) && isValidMultiple(input)) {
submitVerifiedInput(input)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…