카드번호 유효성 검증용으로 사용하기 위해 만들었습니다.

주석은 변수 명으로 대신 합니다.

 

// 룬 알고리즘 validate 검사 (true - 알고리즘 통과, false - 알고리즘 미통과)
const validateLuhnAlgorithm = (cardNumber) => {
	if (!cardNumber || cardNumber.length < 10)	throw new Error("Card number must be at least 10 digits.");
	
	let cardNumberSplitted		= cardNumber.split("");
	let cardNumberSplittedLength	= cardNumberSplitted.length;
	let isRequiresCalculation	= cardNumberSplittedLength % 2 == 0;
	let sumCalculatedCardNumber	= 0;
	
	for (let i=0; i<cardNumberSplittedLength; i++) {
		let cardNumberEach	= Number(cardNumberSplitted[i]);
		let isLastLoop		= i == cardNumberSplittedLength - 1;
        
		if (isLastLoop)		isRequiresCalculation	= false;
		
		if (isRequiresCalculation) {
			cardNumberEach	= cardNumberEach * 2;
			if (cardNumberEach >= 10)	cardNumberEach = cardNumberEach - 9;
		}
		
		isRequiresCalculation	= !isRequiresCalculation;
		
		sumCalculatedCardNumber	+= cardNumberEach;
	}
	
	return sumCalculatedCardNumber % 10 == 0;
};

console.log(validateLuhnAlgorithm('1111111111111117'));
console.log(validateLuhnAlgorithm('4111111111111111'));
console.log(validateLuhnAlgorithm('4000000000000002'));

'Front-Html > Javascript' 카테고리의 다른 글

script background 호출  (0) 2022.05.18
Generator를 이용한 비동기 처리  (0) 2022.01.20
Promise async await를 이용한 비동기 처리  (0) 2022.01.20
javascript querySelector  (0) 2021.03.03
javascript 암복호화 처리  (0) 2016.09.01