Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

38
Vistas
Trouble with Difference Function for Array-based Set Data Structure

(I'm using Group for Set as a name)
if groupA = [1, 2] and groupB = [2, 3]

groupC = groupA.difference(groupB); //-> groupC = [1]  
groupC = groupB.difference(groupA); //-> groupC = [3]  

The former works, but the latter doesn't. Instead of groupC containing 3, it doesn't contain anything. I'm pretty sure all of the other functions work fine. I'm new to JS and I'm not sure what I'm doing wrong.


    class Group
    {
        constructor()
        {
            this.arr = new Array();
        }
        add(elem)
        {
            if(this.has(elem) == false)
            {
                this.arr.push(elem);
            }
        }
        delete(elem)
        {
            for(let i=0; i<this.arr.length; i++)
            {
                if(this.arr[i] == elem)
                {
                    this.arr.splice(i);
                }
            }
        }
        has(elemA)
        {
            for(let elemB of this.arr)
            {
                if(elemA == elemB)
                {
                    return true;
                }
            }
            return false;
        }
        difference(grp)
        {
            var newGroup = new Group();
            for(let i=0; i<this.arr.length; i++)
            {
                newGroup.add(this.arr[i]);
            }
            for(let i=0; i<grp.arr.length; i++)
            {
                newGroup.delete(grp.arr[i]);
            }
            return newGroup;
        }
    }
    
    let a = new Group();
    let b = new Group();
    a.add(1);
    a.add(2);
    b.add(2);
    b.add(3);
    let c = b.difference(a);
    console.log(c.has(1)); //expected false, actually false
    console.log(c.has(2)); //expected false, actually false
    console.log(c.has(3)); //expected true, actually false

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.