Skip to content

Instantly share code, notes, and snippets.

@Atinux
Last active November 29, 2019 18:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Atinux/b65237eb0348fbeb0da3c5dea726a8f7 to your computer and use it in GitHub Desktop.
Save Atinux/b65237eb0348fbeb0da3c5dea726a8f7 to your computer and use it in GitHub Desktop.
Get last digit of an EAN/GTIN 13 in JavaScript
function getLastEan13Digit(ean) {
if (!ean || ean.length !== 12) throw new Error('Invalid EAN 13, should have 12 digits')
const multiply = [1, 3]
let total = 0
ean.split('').forEach((letter, index) => {
total += parseInt(letter, 10) * multiply[index % 2]
})
const base10Superior = Math.ceil(total / 10) * 10
return base10Superior - total
}
console.log(getLastEan13Digit('340093903576'))
@Wyzix33
Copy link

Wyzix33 commented Jun 22, 2019

Thanks

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