From 7d50f43c13131e2942002b55e9c016357b1a94bf Mon Sep 17 00:00:00 2001 From: Rohit Tanwar <31792358+kriadmin@users.noreply.github.com> Date: Wed, 3 Jan 2018 14:32:35 +0530 Subject: [PATCH] Create luhnCheck.md --- snippets/luhnCheck.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 snippets/luhnCheck.md diff --git a/snippets/luhnCheck.md b/snippets/luhnCheck.md new file mode 100644 index 000000000..a6f2cbfd1 --- /dev/null +++ b/snippets/luhnCheck.md @@ -0,0 +1,25 @@ +### luhnCheck + +Implementation of the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc. +Works with numbers and strings alike +``` js +const luhnCheck = num => { + let arr = (num+'').split('').reverse() + let lastDigit = arr.splice(0,1) + let sum = arr.reduce((acc,val,i) => { + val = parseInt(val) + if(i%2!==0) return acc + val + else{ + val = (val * 2)%9 || 9 + return acc+ val } + },0) + sum += parseInt(lastDigit) + return sum%10 === 0 + } +``` +```js + luhnCheck("4485275742308327"); //true + luhnCheck(4485275742308327); //true + luhnCheck(6011329933655299); // true + luhnCheck(123456789); //false +```