satyacode
Background
Back to js-loops

04-bollywood-playlist.js

JavaScript
1/**
2 * 🎵 Simran ki Road Trip Playlist
3 *
4 * Simran aur uske dost road trip pe jaa rahe hain Delhi se Jaipur!
5 * Usne ek playlist banayi hai with song durations (in seconds). Lekin
6 * trip sirf itni der ki hai - usse zyada songs mat daalo playlist mein.
7 *
8 * Rules (use while loop):
9 *   - Songs array mein se ek ek song add karo
10 *   - BEFORE adding a song, check: kya current total + is song ki duration
11 *     maxDuration se zyada ho jayegi? Agar haan, toh STOP. Mat add karo.
12 *   - Agar kisi song ki duration positive number nahi hai (negative, zero,
13 *     NaN, string, etc.), skip that song and move to the next one
14 *   - Continue until all songs are checked or maxDuration limit reached
15 *
16 * Validation:
17 *   - Agar songs array nahi hai, return: { count: 0, totalDuration: 0 }
18 *   - Agar maxDuration positive number nahi hai, return: { count: 0, totalDuration: 0 }
19 *
20 * @param {number[]} songs - Array of song durations in seconds
21 * @param {number} maxDuration - Maximum total duration allowed in seconds
22 * @returns {{ count: number, totalDuration: number }} Songs added and total duration
23 *
24 * @example
25 *   buildPlaylist([240, 180, 300, 200], 600)
26 *   // => { count: 2, totalDuration: 420 }
27 *   // 240 + 180 = 420, next song 300 would make 720 > 600, so stop
28 *
29 *   buildPlaylist([100, -50, 200, 150], 400)
30 *   // => { count: 3, totalDuration: 450 }
31 *   // Wait, 100 + 200 + 150 = 450 > 400? Let me recalculate...
32 *   // 100 added (total=100), skip -50, 200 added (total=300),
33 *   // 150: 300+150=450 > 400, STOP.
34 *   // => { count: 2, totalDuration: 300 }
35 */
36export function buildPlaylist(songs, maxDuration) {
37  if(!Array.isArray(songs) || maxDuration <= 0 || typeof maxDuration !== 'number'){
38    return  {count: 0, totalDuration: 0 }
39  }
40  let count = 0
41  let playlist = []
42  let playListLength = 0
43  let i =0
44  while( i < songs.length){
45    if(songs[i] <= 0 || Number.isNaN(songs[i]) || typeof songs[i] === "string"){
46      i++
47      continue
48    }
49    if(playListLength + songs[i] > maxDuration){
50      break;
51    }
52    playListLength += songs[i]
53    playlist.push(songs[i])
54    count++
55    i++
56  }
57 
58  const totalDuration = playlist.reduce((acc, curr)=> curr + acc, 0)
59  return {count, totalDuration }
60}
61