Sha256: 1ab7c113b4cf437bcb4f06a80cab93183d49fe1f21ba37131531a5175562b56a

Contents?: true

Size: 1.32 KB

Versions: 72

Compression:

Stored size: 1.32 KB

Contents

export default class Luhn {

  constructor(number) {
    this.checkDigit = number % 10;
    this.addends = Luhn.calculateAddends(number);
    this.checksum = Luhn.calculateChecksum(this.addends);
    this.valid = Luhn.determineIfValid(this.checksum);
  }

  static calculateAddends(number) {
    const numberAsString = '' + number + '',
      numbers = [...numberAsString],
      addends = [];

    for (let i = 0; i < numbers.length; i++) {
      const index = numbers.length - 1 - i;
      let currentAddend = parseInt(numbers[index], 10);

      if ((i + 1) % 2 === 0) {
        currentAddend = currentAddend * 2;
        if (currentAddend > 10) {
          currentAddend = currentAddend - 9;
        }
      }
      addends.push(currentAddend);
    }
    return addends.reverse();
  }

  static calculateChecksum(numbers) {
    let sum = 0;
    for (let i = 0; i < numbers.length; i++) {
      sum += numbers[i];
    }
    return sum;
  }

  static determineIfValid(sum) {
    return sum % 10 === 0;
  }

  static create(number) {
    let finalNumber = number * 10,
      luhnNumber = new Luhn(finalNumber),
      index = 0;

    while (!luhnNumber.valid) {
      finalNumber = number * 10 + index;
      luhnNumber = new Luhn(finalNumber);
      if (luhnNumber.valid) {
        break;
      }
      index += 1;
    }
    return finalNumber;
  }
}

Version data entries

72 entries across 72 versions & 1 rubygems

Version Path
trackler-2.0.3.6 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.3.5 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.3.4 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.3.3 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.3.2 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.3.1 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.3.0 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.2.0 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.1.2 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.1.1 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.1.0 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.10 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.9 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.8 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.7 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.6 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.5 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.4 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.3 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.0.2 tracks/ecmascript/exercises/luhn/example.js