Sha256: e98413dc02900d471a33a1349d5458a15e47f4bbeb966d07bb9ac3dad87d5415

Contents?: true

Size: 1.07 KB

Versions: 396

Compression:

Stored size: 1.07 KB

Contents

module.exports = class Luhn
  constructor: (number) ->
    @checkDigit = number % 10
    @addends = @calculateAddends(number)
    @checksum = @calculateChecksum(@addends)
    @valid = @determineIfValid(@checksum)

  calculateAddends: (number) ->

    numberAsString = "" + number + ""
    numbers = numberAsString.split('')

    addends = (@calculateAddend(i,numbers) for i in [0..numbers.length-1])
    addends.reverse()

  calculateAddend: (i,numbers) ->
    index = numbers.length - 1 - i

    currentAddend = parseInt(numbers[index])

    if (i + 1) % 2 == 0
      currentAddend = currentAddend * 2
      if currentAddend > 10
        currentAddend = currentAddend - 9

    currentAddend

  calculateChecksum: (numbers) ->
    numbers.reduce (x,y) -> x + y

  determineIfValid: (sum) ->
    (sum % 10 == 0)


  @create = (number) ->
    finalNumber = number * 10
    luhnNumber = new Luhn(finalNumber)
    index = 0

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

    finalNumber

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.179 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.178 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.177 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.176 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.175 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.174 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.173 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.172 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.171 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.170 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.169 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.167 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.166 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.165 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.164 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.163 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.162 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.161 tracks/coffeescript/exercises/luhn/example.coffee
trackler-2.2.1.160 tracks/coffeescript/exercises/luhn/example.coffee