简体   繁体   中英

How optimize function of counting fractions?

I write function which gets one array from 3 elements (integer, numerator and denominator). It calculate wrong fractions to normal (numerator>denominator).

How optimize this function? I understand that I make many verification, but function looks ugly.

function calculate_measurement(array $m): array
        {
            if (isset($m[NUMERATOR]) && isset($m[DENOMINATOR])) {
                while (intval($m[NUMERATOR]) >= intval($m[DENOMINATOR])) {
                    $m[NUMERATOR] -= $m[DENOMINATOR];
                    if (!isset($m[INTEGER])) {
                        $m[INTEGER] = 0;
                    }
                    ++$m[INTEGER];
                }

                if (0 === $m[NUMERATOR]) {
                    $m[NUMERATOR] = null;
                    $m[DENOMINATOR] = null;
                }
            }

            return $m;
        }

At least, you can rewrite the function like this:

function calculate_measurement(array $m): array
{
   if (!isset($m[INTEGER])) {
            $m[INTEGER] = 0;
   }
   if (!isset($m[NUMERATOR]) || !isset($m[DENOMINATOR])) {
            return $m;
   }
   while (intval($m[NUMERATOR]) >= intval($m[DENOMINATOR])) {
             $m[NUMERATOR] -= $m[DENOMINATOR];
             ++$m[INTEGER];
   }  
   if (0 === $m[NUMERATOR]) {
          $m[NUMERATOR] = null;
          $m[DENOMINATOR] = null;
   }
   return $m;
}

I do not understand the intval() use. Can be numerator/denominator non-integers? I would rather see functions like this:

function calculate_measurement(int $i, int $numerator, int $denominator) : array
{
     while($numerator >= $denominator) {
         $numerator -= $denominator;
         ++$i;
     }
     if(0 === $numerator) {
          $numerator = $denominator = null;
     }
     return [
           INTEGER => $i,
           NUMERATOR => $numerator,
           DENOMINATOR => $denominator
     ];
}

function calculate_measuremenet_arr(array $m): array
{
     if (!isset($m[NUMERATOR]) || !isset($m[DENOMINATOR])) {
        return $m;
     }
     return calculate_measurement(
              $m[INTEGER] ?? 0,
              intval($m[NUMERATOR]),
              intval($m[DENOMINATOR])
     );
}

A loop isn't necessary, just calculate the integer and the new numerator. Something like this should do it:

function calculate_measurement(array $m): array {
    if (!isset($m[NUMERATOR]) || !isset($m[DENOMINATOR])) {
        return $m;
    }

    $m[INTEGER] = intval($m[NUMERATOR] / $m[DENOMINATOR]);
    $m[NUMERATOR] -= ($m[INTEGER] * $m[DENOMINATOR]);

    if ($m[NUMERATOR] === 0) {
        $m[NUMERATOR] = null;
        $m[DENOMINATOR] = null; 
    }

    return $m;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM