Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
Translate this Java method to JavaScript

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))
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda