DEV Community

Discussion on: Wormhole - Data Collection Cheat Sheet and Library in 4 Languages

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Do you know if there's anything juxtlike that would help this case:

There is often a case where I have multiple indexes, so I end up doing something like this:

const cats = [
  { name: "Aeris", id: 0x00, isFavourite: true },
  { name: "Juri", id: 0x01 },
  { name: "Dante", id: 0x03 },
  { name: "Frankenstein", id: 0xff }
]
const byName = new Map()
const byId = new Map()
for (const cat of cats) {
  byName.set(cat.name, cat)
  byId.set(cat.id, cat)
}

If this wasn't as common, I'd probably investigate making a function that takes a predicate and an array and makes an iterator of entries that new Map() can consume.
But like this, I only iterate once to populate multiple Maps.

Plus there's the cases where I receive an object (including from JSON), so normal iteration wouldn't work:

const cats = {
  Aeris: { id: 0x00, isFavourite: true },
  Juri: { id: 0x01 },
  Dante: { id: 0x03 },
  Frankenstein: { id: 0xff }
}
const byName = new Map()
const byId = new Map()
for (const name of Object.keys(cats)) {
  const cat = { name, ...cats[name] }
  byName.set(name, cat)
  byId.set(cat.id, cat)
}

Something like "multiple reducers in one iteration"

Collapse
 
jdsteinhauser profile image
Jason Steinhauser

That is an interesting case that I hadn't considered before. I will definitely have to look into it while exploring JavaScript ecosystem more thoroughly!

Collapse
 
qm3ster profile image
Mihail Malo • Edited

In OOP it would probably be this:

class CatLookup {
  byName = new Map
  byId = new Map
  add(cat) {
    this.byName.set(cat.name, cat)
    this.byId.set(cat.id, cat)
  }
  addMany(cats) {
    for (const cat of cats) this.add(cat)
  }
  constructor(cats = []) {
    this.addMany(cats)
  }
}

const c = new CatLookup([
  { name: "Aeris", id: 0x00, isFavourite: true },
  { name: "Juri", id: 0x01 },
  { name: "Dante", id: 0x03 },
  { name: "Frankenstein", id: 0xff }
])