手撕代码,使用ES6的类实现类似ES6Set的数据结构

es6新增了类的概念,同时也新增了Set这个新的数据结构,
尝试使用类来实现一个类似于Set的集合。
包括has(),add(),delete(),clear(),leys(),values().forEach()这几个方法;
思来想去,觉得好像用到set的地方并不多,数组去重时会用一下,其他地方好像都没怎么用,
我的理解就是set数据结构就是一个所有元素都是唯一的的一个集合;
它接收一个可迭代对象 [iterable]
以下是代码实现:

class SetTest {
    constructor(params = []) {
        this.items = {}
        this.size = 0
        this.init(params)
    }
    init(params) {
        params.forEach(element => {
            this.add(element)
        });
    }
    has(val) {
        return this.items.hasOwnProperty(val)
    }
    add(val) {
        if (!this.has(val)) {
            this.items[val] = val
            this.size++
            return true
        }
        return false
    }
    delete(val) {
        if (this.has(val)) {
            delete this.items[val]
            this.size--
            return true
        }
        return false
    }
    clear() {
        this.items = {}
        this.size = 0
    }
    keys() {
        return Object.keys(this.items)
    }
    values() {
        return Object.values(this.items)
    }
    forEach(fn, context = this) {
        for (let i = 0; i < this.size; i++) {
            let item = Object.keys(this.items)[i];
            fn.call(context, item, item, this.items);
        }
    }
}

测试

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./set.js"></script>
</head>

<body>
    <script>
        const mySet = new SetTest([1, 2, 3, 6, '5', 2, 6, 5])
        console.log(mySet.has('b'), 'has');
        console.log(mySet.add('b'), 'add');
        console.log(mySet.delete(1), 'delete1');
        console.log(mySet.keys(), 'keys');
        mySet.forEach((item, index, ary) => {
            console.log(item);
            console.log(index);
            console.log(ary);
        })
    </script>
</body>

</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值