Skip to content

Instantly share code, notes, and snippets.

@chsh
Created March 2, 2012 11:36
Show Gist options
  • Save chsh/1957920 to your computer and use it in GitHub Desktop.
Save chsh/1957920 to your computer and use it in GitHub Desktop.
Verify EAN and fix if available.
class EAN
valid_code: (ean) ->
return false if ean.match(/[^0-9]/)
ean += '00000' if ean.length == 8
return false unless ean.length == 13
return ean if is_valid(ean)
[ean[1], ean[0]] = [ean[0], ean[1]]
return ean if is_valid(ean)
false
is_valid: (ean) ->
[ean_digits, check_digit] = split_value_and_checkdigit(ean)
even = numberize(ean_digits, [1,3,5,7,9,11])
odd = numberize(ean_digits, [0,2,4,6,8,10])
total = even * 3 + odd
calc_checksum(total) == check_digit
split_value_and_checkdigit: (value) ->
check_digit = value.substring(value.length-1)
origin_digits = value.substring(0, value.length-1)
[origin_digits, check_digit]
numberize: (digits, array) ->
results = Number(digits[index]) for index in array
results.reduce (x, y) -> x + y
calc_checksum: (total) ->
s = total % 10
s = 10 - s if s != 0
s
window.EAN = EAN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment