summary refs log tree commit diff stats
path: root/raku
diff options
context:
space:
mode:
authorAndinus <andinus@nand.sh>2021-09-08 09:43:05 +0530
committerAndinus <andinus@nand.sh>2021-09-08 09:43:05 +0530
commit3ef49dcc8373126736917ce4e94b47f832c47dff (patch)
tree9fb360aaa4a6fa8a6e31adc8c47a7100083a3767 /raku
parent40cd74686ae11a179856f745dfc8c4c4bf3f7dc7 (diff)
downloadexercism-3ef49dcc8373126736917ce4e94b47f832c47dff.tar.gz
Raku: Luhn: Improve solution
- Use regex parameter in `.comb' and skip `.grep'.
- Use a sub subtract-if-greater to reduce noise in ternary operation.
- Remove trailing `;' if implicitly returning a value.
Diffstat (limited to 'raku')
-rw-r--r--raku/luhn/Luhn.rakumod25
1 files changed, 17 insertions, 8 deletions
diff --git a/raku/luhn/Luhn.rakumod b/raku/luhn/Luhn.rakumod
index 8efafc0..2bdaf16 100644
--- a/raku/luhn/Luhn.rakumod
+++ b/raku/luhn/Luhn.rakumod
@@ -1,11 +1,20 @@
 unit module Luhn;
 
-sub is-luhn-valid($input is copy --> Bool) is export {
-    return False if $input.comb.grep(/\d|\s/).join ne $input;
-    $input = $input.comb.grep(/\d/)>>.Int;
-    return False if $input.elems < 2;
-
-    ([+] gather for $input.reverse.kv -> $k, $v {
-         take $k !%% 2 ?? ($_ > 9 ?? $_ - 9 !! $_) !! $v with $v * 2;
-     }) %% 10;
+sub is-luhn-valid(Str $input --> Bool) is export {
+    with $input.comb(/\d|\s/) -> @num-spc {
+        return False if @num-spc.elems !== $input.chars;
+
+        my Int @numbers = @num-spc.comb(/\d/)>>.Int;
+        return False if @numbers.elems < 2;
+
+        ([+] gather for @numbers.reverse.kv -> $k, $v {
+             take $k !%% 2 ?? subtract-if-greater($v * 2, 9) !! $v;
+         }) %% 10
+    }
+}
+
+#| subtract-if-greater will subtract $to-sub from $num if $num is
+#| greater than $to-sub.
+sub subtract-if-greater(Int $num, Int $to-sub --> Int) {
+    $num > $to-sub ?? $num - $to-sub !! $num
 }