您将如何从头开始创建Set.prototype.add()?

时间:2020-07-01 16:42:59

标签: javascript data-structures

ECMAScript上,它说明了如何创建添加原型。

采取以下步骤:

让S为this值。

如果Type(S)不是Object,则抛出TypeError异常。

如果S不具有[[SetData]]内部插槽,则引发TypeError异常。

让条目作为S的[[SetData]]内部插槽的值的列表。

对作为条目元素的每个e重复一次,

如果e不为空并且SameValueZero(e,value)为true,则

返回S。

如果值是-0,则将值设为+0。

将值追加为条目的最后一个元素。

返回S。”

我对JS相当陌生,不知道这意味着什么。如果我要创建一个这样的类

class mySet {
constructor(){
    this.set = {}
}
//adds a value to set
add(){
    
}

我将如何进行?

2 个答案:

答案 0 :(得分:1)

这是一个示例实现。它基本上只是遵循规范中概述的步骤。但是,我不确定是否为空是什么意思,所以(我将其视为undefined。)

要检查是否为负零,您需要作弊并测试-Infinity或类似的东西。

function isNegativeZero (x) {
  return 1 / x === -Infinity
}

function SameValueZero (a, b) {
    if (typeof a !== typeof b) return false

    if (typeof a === 'number') {
        if (Number.isNaN(a) && Number.isNaN(b)) return true;
        if (isNegativeZero(a) && b === 0) return true;
        if (isNegativeZero(b) && a === 0) return true;
        if (+a === +b) return true;
        return false
    }
    return a === b;
}


class MySet {
    constructor(){
        this[MySet.Symbols.SetData] = [];
    }

    //adds a value to set
    add(value){
        const S = this;
        
        if (typeof S !== 'object') throw new TypeError(`Type mismatch. Expected ${this} to be of type object`);

        const entries = this[MySet.Symbols.SetData];
        
        for (const e of entries) {
            if (typeof e !== 'undefined' && SameValueZero(e, value)) return S;
        }

        if (isNegativeZero (value)) value = 0;

        entries.push(value);

        return S;
    }
    toString() {
      return `MySet(${this[MySet.Symbols.SetData].length}) {${this[MySet.Symbols.SetData]}}`
    }
}
MySet.Symbols = {
    SetData: Symbol('SetData')
}


const mySet = new MySet();

mySet.add(1);
console.log(mySet + '');
mySet.add(1);
console.log(mySet + '');
mySet.add(NaN);
console.log(mySet + '');
mySet.add(NaN);
console.log(mySet + '');

答案 1 :(得分:0)

这是个主意。它不适用于# set the height of the row sheet.row_dimensions[1].height = 20 # set the width of the column sheet.column_dimensions['B'].width = 20 ,因为该值用于指示空白。如果改用带孔的数组,则可以与undefined配合使用,但这会降低性能。

在此示例中,该值未附加为数组的最后一个元素,而是附加在第一个空白处,以防止不必要地扩展数组。

当然,JavaScript代码无法访问内部插槽,因此此处使用属性。

undefined