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.6.16 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.15 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.14 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.13 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.12 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.11 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.10 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.9 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.8 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.7 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.6 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.5 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.4 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.3 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.2 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.1 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.6.0 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.5.18 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.5.17 tracks/ecmascript/exercises/luhn/example.js
trackler-2.0.5.16 tracks/ecmascript/exercises/luhn/example.js