I have this Java code below, that I am trying to write its JavaScript equivalent. The code uses a priority queue which is native to Java but not JavaScript. I have attempted to write a similar code in JavaScript but I am not getting the required result. How do I write this, particularly the priority queue section in the Java code. Please note that the required result of this method call is 6
Java Code:
public class Main {
public static void main(String[] args) {
int [] counter = new int[]{3,2,5};
int k=4;
System.out.println(findTotalTime(counter,k));
}
public static int findTotalTime(int[] counter, int k){
//Priority queue section I am mostly curious about
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b)->
(a[0] == b[0] ?
Integer.compare(a[1],b[1]) :
Integer.compare(a[0],b[0])));
for(int i=0;i<counter.length;i++)
pq.add(new int[]{0,i});
int endTime=0;
for(int i=0;i<=k;i++){
int info[] = pq.poll();
int counterTime = info[0];
int index = info[1];
endTime = counterTime + counter[index];
pq.add(new int[]{endTime, index});
}
return endTime;
}
}
My attempt at a JavaScript equivalent:
const findTotalTime = (counter, k) => {
let queue = []
for (let i = 0; i < counter.length; i++) {
queue.push([0, i])
}
queue.sort((a, b) => {return a[0] <= b[0] ? a[1] - b[1] : a[0] - b[0]})
let endTime = 0
for (let i = 0; i <= k; i++) {
let info = queue.shift()
let [counterTime, index] = info
endTime = counterTime + counter[index]
queue.push([endTime, counter[index]])
}
return endTime
}
console.log(findTotalTime([3, 2, 5], 4))