Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

39
Views
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
Answer question
Find remote jobs