We can extended the Set class to serialize and store the information in LocalStorage and keep the data in sync by overriding the add and delete methods of the Set. Like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class localStorageSet extends Set{
    constructor(key){
        super()
        this.key = key
    }


    add(val, raw=false){
        const r = super.add(val)
        if(r && raw == false) this.saveToLocalStorage()
        return r
    }

    delete(val) {
        const r = super.delete(val)
        if(r) this.saveToLocalStorage()
        return r
    }

    saveToLocalStorage(){
        window.localStorage.setItem(this.key, JSON.stringify([...this]))
    }

    // populate set from localStorage
    sync(){
        let self = this
        const storedItem = JSON.parse(window.localStorage.getItem(this.key))

        if(storedItem){
            storedItem.forEach(item => {
                self.add(item, true)
            });
        }
        return self                
    }
}

We can then use it by creating an instance with the key we want to store the Set:

1
let votedFor = new localStorageSet('votedFor')

Then add or delete the keys normally:

1
2
3
4
5
votedFor.add('item-1')
votedFor.add('item-2')
votedFor.add('item-3')

votedFor.delete('item-2')

We can sync the latest state on LocalStorage with what’s on memory by using the sync method:

1
2
votedFor.sync()
votedFor.add('item-4')

Loading back the Set into memory in a different location for eg:

1
2
3
4
let votedFor = new localStorageSet('votedFor')

votedFor.sync()
votedFor.add('item-5')