BaeBox

HashSet(해시셋) with JavaScript 본문

개발 관련

HashSet(해시셋) with JavaScript

배모씨. 2020. 4. 20. 11:55
반응형

* node 에서는 기본적으로 class를 사용하지 못하므로 babel을 사용해야 한다. 적용법은 최하단 링크에 있다. 귀찮으면 아래 링크의 git을 clone을 하시면 된다. 

Set 집합 (이미지 출처 : https://ko.wikipedia.org/wiki/%EC%A7%91%ED%95%A9)

HashSet : Hash를 이용한 Set 기능. 집합이므로 동일한 값들은 무시된다. 

그냥 Set 기능 쓰면 되는데...  왜 하느냐!! 그냥...


class CustomHashSet {

    data = {};
    length = 0;
    // _default = new Date();

    contains = (val) => {
        val = val.toString();
        return (!!this.data[val] && this.data.hasOwnProperty(val));
    };

    add = (val) => {
        if (!this.contains(val.toString())) {
            this.length++;
        }
        this.data[val.toString()] = val;
    };

    remove = (val) => {
        val = val.toString();
        if (!this.contains(val)) {
            return false;
        } else {
            delete this.data[val.toString()];
            this.length--;
            return true;
        }
    };

    clear = () => {
        for (var val in this.data) {
            if (this.data.hasOwnProperty(val)) {
                delete this.data[val];
            }
        }
        this.length = 0;
    }

    isEmpty = () => (this.length === 0);

    getSize = () => this.length;

    toArray = () => {
        const arr = [];
        for (let [key, value] of Object.entries(this.data)) {
            arr.push(value);
        }
        return arr;
    }
}

const cHashSet = new CustomHashSet();
for (let i = 0; i< 10; i++){
    cHashSet.add(`value ${i}`);
}

console.log(cHashSet.toArray());

구글 보니까 이렇게 작성된 코드가 있더라. 내가 살짝 손봤다. 

아쉬운 점이 있는데 정작 제일 중요한 hash 부분을 그냥 JSON을 가져다 썼다는 점이다.

그래서 새로 만들었다. 

const hash = (string, storageSize) => {
    let hash = 0;
    for (let i = 0; i < string.length; i++) hash += string.charCodeAt(i);
    return hash % storageSize;
};


class HashSet {
    storage;
    size;
    constructor(size) {
        this.storage = [];
        this.size = size;
    }

    add(value) {
        const index = hash(value, this.size);
        if (!this.storage[index]) {
            this.storage[index] = [value];
        } else {
            const res = this.storage[index].find(each => each === value);
            res ? null : this.storage[index].push(value);
        }
    }

}


const hSet = new HashSet(23);
for (let i = 0; i < 17; i++){
    hSet.add(`Node ${Math.round(Math.random() * 10)}`);
}

console.log(hSet.storage);

Separate Chaining 방식을 이용하였지만, Object를 사용하지 않고, 배열을 사용하였다. 귀찮았어요


https://github.com/iamdap91/basic-data-structure

 

iamdap91/basic-data-structure

basic-data-structure. Contribute to iamdap91/basic-data-structure development by creating an account on GitHub.

github.com

http://jeonghwan-kim.github.io/2016/07/19/babel.html

 

Babel로 ES6 코드 사용하기

바벨(Babel)을 처음 들은것이 작년이다.ES6 초안이 나온 상황에서 미리 사용해 보고 싶은 이들위해 ES5용 코드로 변환해 주는 기능이다.나는 머지않아 ES6 스펙이 확정될 것이고 더불어 브라우져와 노드에서는 신속히 지원해 줄 것이라 생각했다.그래서 굳이 바벨이라는 툴을 학습할...

jeonghwan-kim.github.io

 

반응형
Comments