美文网首页
9.2 【集合】完善js类(并集/交集/差集/子集)

9.2 【集合】完善js类(并集/交集/差集/子集)

作者: 狩秋之人 | 来源:发表于2019-11-14 19:52 被阅读0次

    继续完善set类

    let Set = require('./set.js');
    
    class fullSet extends Set {
        // 并集
        union (otherSet) {
            let unionSet = new fullSet()
            let values = this.values()
            // 将本身元素注入新集合
            for (let i = 0; i < values.length; i++) {
                unionSet.add(values[i])
            }
            // console.log('第一次循环结束后unionSset的值:' + unionSet.values());
            // 将合并元素注入
            values = otherSet.values();
            for (let i = 0; i < values.length; i++) {
                unionSet.add(values[i])
            }
            // console.log('第二次循环结束后unionSset的值:' + unionSet.values());
            return unionSet
        }
    
        // 交集
        intersection (otherSet) {
            let intersectionSet = new fullSet()
            let values = this.values()
            let temp
    
            // if the otherSet has the same element, push the element to the new set
            for (let i = 0; i < values.length; i++) {
                (otherSet.has(values[i])) ? intersectionSet.add(values[i]): ''
            }
            return intersectionSet
        }
    
        // 差集
        difference (otherSet) {
            let differenceSet = new fullSet(),
                values = this.values(),
                temp
    
            for (let i = 0; i < values.length; i++) {
                otherSet.has(values[i])? '' : differenceSet.add(values[i])            
            }
    
            return differenceSet
        }
    
        // 判断是否为子集
        sub (otherSet) {
            let values = this.values()
            let judgement;
    
            for (let i = 0; i < values.length; i++) {
                judgement = otherSet.has(values[i])
                if (!judgement) {
                   return false 
                }
            }
            return true
        }
    }
    
    let temp;
    let a = new fullSet()
    a.add(1)
    a.add(2)
    a.add(3)
    a.add(4)
    a.add(5)
    let b = new fullSet()
    b.add(2)
    b.add(3)
    b.add(4)
    b.add(5)
    b.add(6)
    b.add(7)
    b.add(8)
    
    console.log('TEST1: union');
    temp = a.union(b)
    console.log(temp.values());
    
    console.log('TEST2: intersection');
    temp = a.intersection(b)
    console.log(temp.values());
    
    console.log('TEST3: difference');
    temp = a.difference(b)
    console.log(temp.values());
    
    console.log('TEST4: subset');
    temp = a
    temp = a.sub(a)
    console.log(temp)
    

    相关文章

      网友评论

          本文标题:9.2 【集合】完善js类(并集/交集/差集/子集)

          本文链接:https://www.haomeiwen.com/subject/msldictx.html