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: 元の配列を変更せず、新しい配列を返す
- resolution計算: width × height で解像度を求める
- 降順ソート: resolution が大きい順に並べる
使用例
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