Sha256: 9e51474035cce8c8df4ef1a833522f2398484894f0a467687bd4cb545ae97086

Contents?: true

Size: 826 Bytes

Versions: 66

Compression:

Stored size: 826 Bytes

Contents

local Luhn = {}
Luhn.__index = Luhn

function Luhn:check_digit()
  return tonumber(self.s:sub(-1))
end

function Luhn:addends()
  local result = {}
  for i = #self.s, 1, -1 do
    local digit = tonumber(self.s:sub(i, i))
    if #result % 2 > 0 then digit = digit * 2 end
    if digit > 9 then digit = digit - 9 end
    table.insert(result, 1, digit)
  end
  return result
end

function Luhn:checksum()
  local checksum = 0
  for _, addend in ipairs(self:addends()) do
    checksum = checksum + addend
  end
  return checksum
end

function Luhn:valid()
  return self:checksum() % 10 == 0
end

local function new(s)
  return setmetatable({ s = s }, Luhn)
end

local function create(s)
  local checksum = new(s .. '0'):checksum()
  return s .. tostring((10 - (checksum % 10)) % 10)
end

return {
  new = new,
  create = create
}

Version data entries

66 entries across 66 versions & 1 rubygems

Version Path
trackler-2.0.6.10 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.9 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.8 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.7 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.6 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.5 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.4 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.3 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.2 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.1 tracks/lua/exercises/luhn/example.lua
trackler-2.0.6.0 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.18 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.17 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.16 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.15 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.14 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.13 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.12 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.11 tracks/lua/exercises/luhn/example.lua
trackler-2.0.5.10 tracks/lua/exercises/luhn/example.lua