Twitter 동영상 같은 미디어를 해상도 기준으로 정렬할 때 작성한 코드다.
해상도(너비 × 높이) 기준 내림차순 정렬
interface MediaFile { url: string; height: number; width: number}
function sortMediaByQuality(files: Array<MediaFile>): Array<MediaFile> { return files.toSorted((a, b) => { const resolutionA = a.width * a.height; const resolutionB = b.width * b.height; return resolutionB - resolutionA });}포인트
toSorted: 원본 배열을 변경하지 않고 새 배열을 반환한다- 해상도 계산:
width × height로 해상도를 구한다 - 내림차순 정렬: 해상도가 큰 순서대로 정렬한다
사용 예시
const videos: MediaFile[] = [ { url: "video1.mp4", width: 1280, height: 720 }, // 921,600 { url: "video2.mp4", width: 1920, height: 1080 }, // 2,073,600 { url: "video3.mp4", width: 640, height: 480 }, // 307,200];
const sorted = sortMediaByQuality(videos);// video2.mp4 (1920x1080) 가 가장 먼저 온다요약
해상도 계산과 정렬을 조합하면 고화질 미디어 파일을 우선적으로 선택할 수 있다.
Twitter 동영상처럼 여러 해상도의 영상이나 이미지 중 최적의 파일을 고를 때 유용하다.
hsb.horse