Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

extend keys() and other generator method of Map Class in javascript

I need to use an object as keys for my map, therefore I extended the map class that stringifies the object passed, like so

class CoordMapper extends Map {
    set = (k: ISquareCoordinate, v: Array<ISquareCoordinate>) => {
        const stringifiedKey = JSON.stringify(k)
        return super.set(stringifiedKey,v)
    }

    get = (k: ISquareCoordinate) => {
        const stringifiedKey = JSON.stringify(k)
        return super.get(stringifiedKey)
    }
}

As far as I understand that keys(), values() and entries() are generator methods, therefore I can do something like

* keys() {
   const keysArr = [...super.keys()]
   for (const key of keysArr){
      yield JSON.parse(key)
   }
}

But this causes me to load all the keys which I wish to avoid, is there a better way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT:
While Map does take in objects as keys but it only checks objects by reference. As an example

let newMap = Map()
const obj1 = {'a': 1, 'b' :2}
newMap.set(obj1, 123)
const copyObj1 = {...obj1}
console.log(newMap.get(obj1)) //returns 123
console.log(newMap.get(copyObj1)) //returns undefined

And i need the second console.log to return 123 aswell

>Solution :

Rather than collecting all the parent values into an array, just iterate over them directly:

* keys() {
   const parentKeyIterator = super.keys();
   for (const key of parentKeyIterator){
      yield JSON.parse(key)
   }
}

That way, the laziness of the iterator is retained: each time next() is called on your extended iterator, it will call next() on parentKeyIterator once, then reach your yield statement, and pause.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading