I'm calling a Javascript library and getting a Map Iterator back (which in Javascript you use with for ... in)
How do I turn this into a ClojureScript sequence so I can call for on it?
I'm calling a Javascript library and getting a Map Iterator back (which in Javascript you use with for ... in)
How do I turn this into a ClojureScript sequence so I can call for on it?
Copyright © 2021 Jogjafile Inc.
By looking at the MDN documentation on Map iterator you can check that you can navigate the iterator with the
.next()method which will return a JS object with 2 properties:valueanddone, wherevaluewill contain an Array of size 2 with the key and value for each entry on the Map, anddone, which will be false until the iterator is exhausted (no more entries).Using this, we can create a ClojureScript function that takes the iterator and builds a Map (or a ClojureScript map if you remove the
clj->js).I used the
^:exportmetadata flag so that you can call the function from the console. If you save this function in sayapp/main.cljs, the function will be available asapp.main.iterToMap()in the global JS object.You can use it as follows in the Developer Console:
If you want a sequence of key-value pairs, you can use the same principle to create a lazy-sequence, you just need to remember to hold a reference to the iterator so you can extract the next item.