summary refs log tree commit diff stats
path: root/javascript/luhn/luhn.js
diff options
context:
space:
mode:
authorAndinus <andinus@nand.sh>2021-09-05 22:23:27 +0530
committerAndinus <andinus@nand.sh>2021-09-05 22:23:27 +0530
commit670546b8a284bee51f63f00dabcf89b9ea463e68 (patch)
tree3d50372887f2931eb714405a12aeafad28049aa1 /javascript/luhn/luhn.js
parent27d42698a76605b0653474e8d0d0976b74cd2b88 (diff)
downloadexercism-670546b8a284bee51f63f00dabcf89b9ea463e68.tar.gz
JS: Luhn: Add solution
Diffstat (limited to 'javascript/luhn/luhn.js')
-rw-r--r--javascript/luhn/luhn.js34
1 files changed, 34 insertions, 0 deletions
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);
+};