556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / js-min-max-loop.md
2.2 KB
1--- 2title: Use Loop for Min/Max Instead of Sort 3impact: LOW 4impactDescription: O(n) instead of O(n log n) 5tags: javascript, arrays, performance, sorting, algorithms 6--- 7 8## Use Loop for Min/Max Instead of Sort 9 10Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower. 11 12**Incorrect (O(n log n) - sort to find latest):** 13 14```typescript 15interface Project { 16 id: string 17 name: string 18 updatedAt: number 19} 20 21function getLatestProject(projects: Project[]) { 22 const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt) 23 return sorted[0] 24} 25``` 26 27Sorts the entire array just to find the maximum value. 28 29**Incorrect (O(n log n) - sort for oldest and newest):** 30 31```typescript 32function getOldestAndNewest(projects: Project[]) { 33 const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt) 34 return { oldest: sorted[0], newest: sorted[sorted.length - 1] } 35} 36``` 37 38Still sorts unnecessarily when only min/max are needed. 39 40**Correct (O(n) - single loop):** 41 42```typescript 43function getLatestProject(projects: Project[]) { 44 if (projects.length === 0) return null 45 46 let latest = projects[0] 47 48 for (let i = 1; i < projects.length; i++) { 49 if (projects[i].updatedAt > latest.updatedAt) { 50 latest = projects[i] 51 } 52 } 53 54 return latest 55} 56 57function getOldestAndNewest(projects: Project[]) { 58 if (projects.length === 0) return { oldest: null, newest: null } 59 60 let oldest = projects[0] 61 let newest = projects[0] 62 63 for (let i = 1; i < projects.length; i++) { 64 if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i] 65 if (projects[i].updatedAt > newest.updatedAt) newest = projects[i] 66 } 67 68 return { oldest, newest } 69} 70``` 71 72Single pass through the array, no copying, no sorting. 73 74**Alternative (Math.min/Math.max for small arrays):** 75 76```typescript 77const numbers = [5, 2, 8, 1, 9] 78const min = Math.min(...numbers) 79const max = Math.max(...numbers) 80``` 81 82This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.