Search code examples
javascriptarraysindexof

The Supermarket Queue - Javascript Best Practice Solution


On my travel on learning basic javascript, I have come across the Code Wars Website, which confronts one with different problems. I'm very new to JavaScript development and Code Wars has been of major help in understanding the basic js logic, by studying the best practice solutions for those problems and trying to reconstruct and understand them. With the help of google, youtube etc. I have managed to understand most of the best practice solutions and it has helped me to further my understanding of javascript, although I have now come across a Problem - and a best practice solution - but I just can't wrap my head around its logic and how it works. I'd be very thankful to anyone that could explain the best practice solution in words for dummies.

Problem: There is a queue for the self-checkout tills at the supermarket. Your task is to write a function to calculate the total time required for all the customers to check out! All instructions can be found on the CodeWars Page: https://www.codewars.com/kata/57b06f90e298a7b53d000a86/train/javascript

The best practice solution looks like this:

function queueTime(customers, n) {
  var w = new Array(n).fill(0);
  for (let t of customers) {
    let idx = w.indexOf(Math.min(...w));
    w[idx] += t;
    
  }
  return Math.max(...w);
}

Sample Test:

Test.describe("example tests", function() {
Test.assertEquals(queueTime([], 1), 0);
Test.assertEquals(queueTime([1,2,3,4], 1), 10);
Test.assertEquals(queueTime([2,2,3,3,4,4], 2), 9);
Test.assertEquals(queueTime([1,2,3,4,5], 100), 5);

//add some more example tests here, if you like

})

The main struggle I am having is that I dont understand how the 'w' variable interacts with the 'for of' function. In my understanding, 'w' is an Array filled with zeros, so how does the w.indexOf Method find a min. value to add to idx variable? In general I would be very thankful for anyone that could breakdown the best practice solution.

Thanks, Jerome


Solution

  • Initially w is an array filled with 0s

    The code then sets idx to the index of the lowest value.

    First time that index would be 0

    let idx = [0,0,0,0,0].indexOf(Math.min([0,0,0,0,0])); // 0

    So w[0] += t becomes [1,0,0,0,0] for t === 1

    next time:

    let idx = [1,0,0,0,0].indexOf(Math.min([1,0,0,0,0])); // 1

    So w[1] += t becomes [1,2,0,0,0] for t === 2

    and so on