Skip to content

Instantly share code, notes, and snippets.

@hillerstorm
Forked from 140bytes/LICENSE.txt
Last active December 24, 2015 15:49
Show Gist options
  • Save hillerstorm/6823202 to your computer and use it in GitHub Desktop.
Save hillerstorm/6823202 to your computer and use it in GitHub Desktop.
Calculate checksum using the Luhn Algorithm

Calculate checksum using the Luhn Algorithm

Calculates the checksum of a given input of numbers using the Luhn Algorithm

75bytes

function(
a, // input number sequence as a string
b, // placeholder
c, // --||--
d){ // --||--
c=0;
// traverse the input and multiply every other digit
for(b in a)
d=a[b],c+=
b%2?+d // every other digit is just used straight away
:d*2%10|d/5; // digits above 5 will result in double digits when
// multiplied with 2 and should be added together
//
// 5*2 = 10 -> 1+0 = 1
// 6*2 = 12 -> 1+2 = 3
// 7*2 = 14 -> 1+4 = 5
// 8*2 = 16 -> 1+6 = 7
// 9*2 = 18 -> 1+8 = 9
//
// digits below 5 are just multiplied by 2
// and this, is magic
// multiply the sum by 9 and return the last digit
return c*9%10
}
function(a,b,c,d){c=0;for(b in a)d=a[b],c+=b%2?+d:d*2%10|d/5;return c*9%10}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Johan Hillerström <https://github.com/hillerstorm>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "luhnAlgorithm",
"description": "Calculates a checksum using the Luhn algorithm.",
"keywords": [
"luhn",
"algorithm",
"formula",
"checksum"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>6</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var luhn = function(a,b,c,d){c=0;for(b in a)d=a[b],c+=b%2?+d:d*2%10|d/5;return c*9%10}
document.getElementById('ret').innerHTML = luhn('811218987')
</script>
@hillerstorm
Copy link
Author

:D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment