Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify logic of number_to_roman function #5270

Merged
merged 1 commit into from
Nov 1, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 24 additions & 67 deletions system/Helpers/number_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,79 +182,36 @@ function format_number(float $num, int $precision = 1, ?string $locale = null, a
*/
function number_to_roman(string $num): ?string
{
static $map = [
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1,
];

$num = (int) $num;

if ($num < 1 || $num > 3999) {
return null;
}

$_number_to_roman = static function ($num, $th) use (&$_number_to_roman) {
$return = '';
$key1 = null;
$key2 = null;

switch ($th) {
case 1:
$key1 = 'I';
$key2 = 'V';
$keyF = 'X';
break;

case 2:
$key1 = 'X';
$key2 = 'L';
$keyF = 'C';
break;

case 3:
$key1 = 'C';
$key2 = 'D';
$keyF = 'M';
break;

case 4:
$key1 = 'M';
break;
}
$n = $num % 10;

switch ($n) {
case 1:
case 2:
case 3:
$return = str_repeat($key1, $n);
break;
$result = '';

case 4:
$return = $key1 . $key2;
break;

case 5:
$return = $key2;
break;

case 6:
case 7:
case 8:
$return = $key2 . str_repeat($key1, $n - 5);
break;

case 9:
$return = $key1 . $keyF; // @phpstan-ignore-line
break;
}

switch ($num) {
case 10:
$return = $keyF; // @phpstan-ignore-line
break;
}
if ($num > 10) {
$return = $_number_to_roman($num / 10, ++$th) . $return;
}

return $return;
};
foreach ($map as $roman => $arabic) {
$repeat = (int) floor($num / $arabic);
$result .= str_repeat($roman, $repeat);
$num %= $arabic;
}

return $_number_to_roman($num, 1);
return $result;
}
}