Find max number of items that can fit in a given max-width Given a list of elements, each with own width, and a max-width.
I need to find how many elements can be fit inside that max-width, keeping the order of the elements.

Some examples:


elements: { width: 10 }, { width: 20 }
max-width: 30
result count should be 2, because both elements can be fit in this max-width    
elements: { width: 10 }, { width: 20 }
max-width: 5
result count should be 0, because first element cannot be fit in this max-width    
elements: { width: 10 }, { width: 20 }, { width: 5 }
max-width: 20
result count should be 1, because adding the second element exceed the max-width.    


This piece of javascript code solve it, but I feel it is not readable enough:



function getNumberOfElementsInWidth(elements, maxWidth) { 
  let accWidth = 0;
  let count = 0;
  for (let i = 0; i&lt;elements.length; i++) {
    if (accWidth + elements[i].width &lt;= maxWidth) {
      accWidth = accWidth + elements[i].width;
      count++;
    } else {
      break;
    }
  }
  return count;
}

function doSample() {
  const elements = [ { width: 10 }, { width: 12 }, { width: 15 } ];
  const maxWidth = 100;
  
  console.log(getNumberOfElementsInWidth(elements, maxWidth));
}

doSample();




I would appreciate your feedback on how to make the code for getNumberOfElementsInWidth function clearer.
I find your code clear enough, but you could improve it a little bit, so you only do the add operation once:

function getNumberOfElementsInWidth(elements, maxWidth) {
  let accWidth = 0;
  let count = 0;
  for (let i = 0; i &lt; elements.length; i++) {
    accWidth += elements[i].width
    if (accWidth &lt;= maxWidth) {
      count++;
    } else {
      break;
    }
  }
  return count;
}




Further you could reverse the conditional statement:

function getNumberOfElementsInWidth(elements, maxWidth) {
  let accWidth = 0;
  let count = 0;
  for (let i = 0; i &lt; elements.length; i++) {
    accWidth += elements[i].width
    if (accWidth &gt; maxWidth) {
      break;
    }

    count++;
  }
  return count;
}




In a more condensed version you could make the count variable also be the index:

function getNumberOfElementsInWidth(elements, maxWidth) {
  let accWidth = 0;

  for (var count = 0; count &lt; elements.length; count++) {
    if ((accWidth += elements[count].width) &gt; maxWidth) {
      break;
    } 
  }
  return count;
}


Be aware that count must be declared as var count = 0 not let count = 0