Skip to content

Instantly share code, notes, and snippets.

@salman0ansari
Created September 10, 2024 07:18
Show Gist options
  • Save salman0ansari/d7620a9bd616d39773f5af974ce737df to your computer and use it in GitHub Desktop.
Save salman0ansari/d7620a9bd616d39773f5af974ce737df to your computer and use it in GitHub Desktop.
Luhn's Algorithm
// https://x.com/cneuralnetwork/status/1831989042826629546
const digits = "4137894711755904";
let sum = [];
digits.split("").map((digit, index) => {
if (index % 2 === 0) {
const double = +digit * 2;
if (double > 9) {
let pushItem = String(double)
.split("")
.reduce((a, b) => +a + +b);
sum.push(pushItem);
} else {
sum.push(double);
}
} else {
sum.push(+digit);
}
});
console.log(
String(sum.reduce((a, b) => a + b, 0)).endsWith("0") ? "Valid" : "Invalid"
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment