Skip to content

Commit 8aae3f8

Browse files
committed
Refactor findMax to eliminate unnecessary array filtering
1 parent 45d4be7 commit 8aae3f8

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

Sprint-1/implement/max.js

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,16 @@ function findMax(elements) {
22
if (!Array.isArray(elements) || elements.length === 0) {
33
return -Infinity;
44
}
5-
const numbers = elements.filter(
6-
(x) => typeof x === "number" && Number.isFinite(x)
7-
);
8-
// Filters out all non-numeric values
9-
if (numbers.length === 0) return -Infinity;
10-
// Matches empty array behavior
11-
let max = -Infinity; // All negative and positive numbers are greater than this minimum starting value
12-
for (const n of numbers) {
13-
// Loops through each n in array, if greater than max, assigns n to max
14-
if (n > max) max = n;
15-
}
16-
return max;
5+
let max = -Infinity;
6+
7+
for (const x of elements) {
8+
if (typeof x === "number" && Number.isFinite(x)) {
9+
if (x > max) max = x;
10+
}
11+
}
12+
13+
return max;
14+
// removed .filter as this creates a new array so this avoids unnecessary clones
1715

1816
}
1917

0 commit comments

Comments
 (0)