“Algoritmo Luhn JavaScript” Respostas de código

Algoritmo Luhn JavaScript

/*
HTML:
<form action="">
      <label for="cardNum">Card Number</label><br>
      <input type="text" id="cardNum" placeholder="Please type your credit card number here..."><br>
</form>
<button onclick="checkIfPassLuhn()" class="checker">Check if the above number passes the Luhn Algorithm</button>
*/

function checkIfPassLuhn() {
    var num = document.getElementById("cardNum").value;
    var array = (num + '').split('').reverse().map(x => parseInt(x));
    var theLastDig = array.shift();
    let sum = array.reduce((prevVal, curVal, index) => (index % 2 !== 0 ? prevVal + curVal : prevVal + ((curVal *= 2) > 9 ? curVal - 9 : curVal)), 0);
    sum += theLastDig;
    if(sum % 10 === 0){
        alert("Your number is correct!");
    }else{
        alert("Your number is incorrect");
    }
}
//Call the method with an HTML element
Fair Flamingo

Algoritmo Luhn JavaScript

/**
 * Luhn algorithm in JavaScript: validate credit card number supplied as string of numbers
 * @author ShirtlessKirk. Copyright (c) 2012.
 * @license WTFPL (http://www.wtfpl.net/txt/copying)
 */
var luhnChk = (function (arr) {
    return function (ccNum) {
        var 
            len = ccNum.length,
            bit = 1,
            sum = 0,
            val;

        while (len) {
            val = parseInt(ccNum.charAt(--len), 10);
            sum += (bit ^= 1) ? arr[val] : val;
        }

        return sum && sum % 10 === 0;
    };
}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]));
Undefined

Respostas semelhantes a “Algoritmo Luhn JavaScript”

Perguntas semelhantes a “Algoritmo Luhn JavaScript”

Mais respostas relacionadas para “Algoritmo Luhn JavaScript” em JavaScript

Procure respostas de código populares por idioma

Procurar outros idiomas de código