我目前正在开展涉及验证信用卡的项目,我有这个luhn算法:
export default function luhn(card: string): boolean {
return (
card.split('').reduceRight(function(prev: any, curr: any, idx) {
prev = parseInt(prev, 10)
if ((idx + 1) % 2 !== 0) {
curr = (curr * 2)
.toString()
.split('')
.reduce(function(p, c) {
return (parseInt(p, 10) + parseInt(c, 10)) as any
})
}
return prev + parseInt(curr, 10)
}, 0) %
10 ===
0
)
}
注意那里的布尔值?我使用它作为我的index.ts的模块,如下所示:
import { createReadStream } from 'fs'
import { createInterface } from 'readline'
import { getCompanyName } from './cardType'
import cardValidator from './cardValidator'
const lineReader = createInterface({
input: createReadStream('data/input.txt')
})
lineReader.on('line', (creditCard: string) => {
var company = `${getCompanyName(creditCard)}: ${creditCard} (${cardValidator(
creditCard
)})`
console.log(company)
})
它目前向控制台输出如下内容:
MasterCard: 5105105105105100 (true)
MasterCard: 5105105105105106 (false)
我希望true / false有效/无效我已经对它进行了一些调查(w3)但是我不知道如何将任何东西集成到我的算法中,因为它需要你声明一个变量无论是真还是假。任何建议/答案将不胜感激