Luhn algorithm

Compact view

Benchmark publishedon

Description

Comparing various implementations of the Luhn algorithm.

Setup

 function luhn(input) {
    const precomputed = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
    let sum = 0;
    let isSecond = 0;
    let length = input.length;
    while (length) {
        const num = input.charCodeAt(--length) - 48;
        sum += isSecond ? precomputed[num] : num;
        isSecond ^= 1;
    }
    return sum % 10 === 0;
}

function isLuhnAlgo(digits) {
  let length = digits.length;
  let bit = 1;
  let sum = 0;
  while (length) {
    const value = +digits[--length];
    bit ^= 1;
    sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;
  }
  return sum % 10 === 0;
}

Test Runner

Initializing...

Testing in
Test CaseOps/sec
luhn()
luhn('4000000000001000');
ready
isLuhnAlgo()
isLuhnAlgo('4000000000001000');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

Revision 1
publishedon