79125371

Date: 2024-10-25 10:59:40
Score: 1
Natty:
Report link

I tweaked the code slightly with the following inclusions:

  1. Rejigged sorted data indexes by returning values(), instead of the collection as-is
  2. It made more sense to average the scores in either mode, since the indices don't make much sense to the viewer. It provides greater clarity into what the ranking is all about. I compared returned result set with the actual row values and the ranking for the employees in each mode checks out

In addition, the sorting function is not entirely redundant as earlier assumed, since the behavior varies, depending on incoming parameter

Putting it all together, we have:

protected function punctualChart ($attendanceCollection, ?string $puncMode) {

        $puncMode = $puncMode?? "ear";

        $attendanceDays = $attendanceCollection->groupBy(function ($attendance) {

            return $attendance->created_at->format("m-d");
        })
        ->map(function ($daysCollection) use ($puncMode) { // then sum their value for each day? add their indexes. depending on the mode, we know whether highest or lowest is the winner

            return $puncMode == "ear"? $daysCollection->sortByDesc("created_at")->values():

            $daysCollection->sortBy("created_at")->values();
        });
//dd($attendanceDays, $puncMode);
        $scoreEmployee = [];

        $maxValue = 0;

        foreach ($attendanceDays as $attendanceCollection) {

            foreach ($attendanceCollection as $index => $attendance) {

                $employeeId = /*$attendance->employee->last_name.*/$attendance->employee_id;

                if (!array_key_exists($employeeId, $scoreEmployee))

                    $scoreEmployee[$employeeId] = /*0;*/[

                        "value" => 0,

                        "model" => $attendance->employee, //->last_name
                    ];

                $maxValue += $index+1;

                $scoreEmployee[$employeeId]["value"] += $index+1; // offset 0-based index
            }
        }

        foreach ($scoreEmployee as $employeeId => &$employeeDetails)

            $employeeDetails["value"] = round(

                ($employeeDetails["value"]/$maxValue)*100,

                2
            );
//dd($scoreEmployee);
        return $scoreEmployee;
    }

Thanks to @angel for motivating me to give this another shot

reassign the indexes to the resulting collection

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @angel
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: I Want Answers