From dca1846ee1104f506f1082bd1f34a9911da4563a Mon Sep 17 00:00:00 2001 From: Vano Devium Date: Wed, 22 Apr 2020 21:10:58 +0300 Subject: [PATCH] Two little improvements - removed unnecessary operation from the cycle; - switched to decrement; --- src/Luhn/Algorithm/LuhnAlgorithm.php | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Luhn/Algorithm/LuhnAlgorithm.php b/src/Luhn/Algorithm/LuhnAlgorithm.php index 37fbad4..db32fc0 100644 --- a/src/Luhn/Algorithm/LuhnAlgorithm.php +++ b/src/Luhn/Algorithm/LuhnAlgorithm.php @@ -36,11 +36,11 @@ public function computeCheckDigit(string $input): int public function computeCheckSum(string $input): int { // Need to account for the check digit. - $nDigits = \strlen($input) + 1; - $parity = $nDigits % 2; + $nDigits = \strlen($input); + $parity = ($nDigits + 1) % 2; $checksum = 0; - for ($i = 0; $i < $nDigits - 1; ++$i) + for ($i = 0; $i < $nDigits; ++$i) { $digit = (int)$input[$i]; @@ -68,10 +68,12 @@ protected function cleanAndSplitInput(string $input): array if ($inputLength === 0) { throw new InvalidArgumentException; } - + + $inputLength--; + return [ - \substr($input, 0, $inputLength - 1), - (int)$input[$inputLength - 1], + \substr($input, 0, $inputLength), + (int)$input[$inputLength], ]; } }