From 670546b8a284bee51f63f00dabcf89b9ea463e68 Mon Sep 17 00:00:00 2001 From: Andinus Date: Sun, 5 Sep 2021 22:23:27 +0530 Subject: JS: Luhn: Add solution --- javascript/luhn/luhn.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 javascript/luhn/luhn.js (limited to 'javascript/luhn/luhn.js') diff --git a/javascript/luhn/luhn.js b/javascript/luhn/luhn.js new file mode 100644 index 0000000..166a0bf --- /dev/null +++ b/javascript/luhn/luhn.js @@ -0,0 +1,34 @@ +'use strict'; + +export const valid = (input) => { + let filtered = []; + + // Filter the numbers out. Return false if we find anything other + // than numbers or spaces. + for (let idx = 0; idx < input.length; idx++) { + if (/^\d$/.test(input[idx])) + filtered.push(Number(input[idx])); + else if (!(/^\s$/.test(input[idx]))) + return false; + } + + // Invalid. + if (filtered.length < 2) + return false; + + // Reverse the filtered numbers. + filtered.reverse(); + + let sum = 0; + for (let idx = 0; idx < filtered.length; idx++) { + if ((idx % 2) !== 0) { + if ((filtered[idx] * 2) > 9) + sum += (filtered[idx] * 2) - 9; + else + sum += filtered[idx] * 2; + } else + sum += filtered[idx]; + } + + return (sum % 10 === 0); +}; -- cgit 1.4.1-2-gfad0