Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/js-min-max-loop.md
1---2title: Use Loop for Min/Max Instead of Sort3impact: LOW4impactDescription: O(n) instead of O(n log n)5tags: javascript, arrays, performance, sorting, algorithms6---78## Use Loop for Min/Max Instead of Sort910Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.1112**Incorrect (O(n log n) - sort to find latest):**1314```typescript15interface Project {16id: string17name: string18updatedAt: number19}2021function getLatestProject(projects: Project[]) {22const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)23return sorted[0]24}25```2627Sorts the entire array just to find the maximum value.2829**Incorrect (O(n log n) - sort for oldest and newest):**3031```typescript32function getOldestAndNewest(projects: Project[]) {33const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)34return { oldest: sorted[0], newest: sorted[sorted.length - 1] }35}36```3738Still sorts unnecessarily when only min/max are needed.3940**Correct (O(n) - single loop):**4142```typescript43function getLatestProject(projects: Project[]) {44if (projects.length === 0) return null4546let latest = projects[0]4748for (let i = 1; i < projects.length; i++) {49if (projects[i].updatedAt > latest.updatedAt) {50latest = projects[i]51}52}5354return latest55}5657function getOldestAndNewest(projects: Project[]) {58if (projects.length === 0) return { oldest: null, newest: null }5960let oldest = projects[0]61let newest = projects[0]6263for (let i = 1; i < projects.length; i++) {64if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]65if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]66}6768return { oldest, newest }69}70```7172Single pass through the array, no copying, no sorting.7374**Alternative (Math.min/Math.max for small arrays):**7576```typescript77const numbers = [5, 2, 8, 1, 9]78const min = Math.min(...numbers)79const max = Math.max(...numbers)80```8182This 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.83