Skip to content

Commit ca96112

Browse files
committed
Optimize orderBy() method
1 parent 17f30a8 commit ca96112

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

src/AssociativeArray.php

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -156,23 +156,28 @@ public function orderBy($keys, $directions = 'asc')
156156
$keys = (array)$keys;
157157
}
158158

159-
$i = 0;
160-
$key2Direction = [];
161-
$isStringDirections = is_string($directions);
159+
$key2IsDesc = [];
162160

163-
foreach ($keys as $key) {
164-
$key2Direction[$key] = $isStringDirections ? $directions : ($directions[$i] ?? 'asc');
165-
$i++;
161+
if (is_string($directions)) {
162+
$isDesc = $directions === 'desc';
163+
foreach ($keys as $key) {
164+
$key2IsDesc[$key] = $isDesc;
165+
}
166+
} else {
167+
$i = 0;
168+
foreach ($keys as $key) {
169+
$key2IsDesc[$key] = (($directions[$i++] ?? 'asc') === 'desc');
170+
}
166171
}
167172

168173
$result = $this->rows;
169174

170-
usort($result, function($a, $b) use ($keys, $key2Direction) {
175+
usort($result, function($a, $b) use ($keys, $key2IsDesc) {
171176
foreach ($keys as $key) {
172-
if ($cmpVal = $key2Direction[$key] === 'desc'
177+
if ($comparedResult = $key2IsDesc[$key]
173178
? $b[$key] <=> $a[$key]
174179
: $a[$key] <=> $b[$key]) {
175-
return $cmpVal;
180+
return $comparedResult;
176181
}
177182
}
178183
return 0;

0 commit comments

Comments
 (0)