Can't Figure Out How To Write Loop

Maybe something like?

function canBuyAlbum (money, album) {
  return album.price <= money
}

function buyAlbum (money, album) {
  album.purchase()
  cart.add(album) 
  return money - album.price
}

function buyAlbums (money, albums) {
  if (!albums.length) return money
  var album = albums.pop()
  if (!canBuyAlbum(money, album)) return money
  return buyAlbums(buyAlbum(money, album), albums)
}

if you are using something like babel it will optimize the recursion for you, otherwise you will have to do something like this instead

function buyAlbums (money, albums) {
  __loop: while(1) {
    if (!albums.length) return money
    var album = albums.pop()
    if (!canBuyAlbum(money, album)) return money
    money = buyAlbum(money, album)
    continue __loop
  }
}
1 Like