D
D
dom1n1k2017-05-01 19:50:27
JavaScript
dom1n1k, 2017-05-01 19:50:27

What is the easiest way to get an element from a Set/Map collection?

How to get the first element from an object of type Set or Map? But generally speaking, not necessarily the first, you can arbitrary - the last, from the middle, at least some.
Anticipating the flood on the topic that Set was not invented for this, etc. - I will immediately explain the goal.
Some function receives a collection of objects as input. The nuance is that objects do not always have a permanent structure. Therefore, the function first of all wants to get one sample from the set and check for the presence of some fields there. Depending on the results, different algorithms can then be used.
Generally speaking, the question looks stupid, because the specification provides tools for this:
https://developer.mozilla.org/ru/docs/Web/JavaScri...
But we have a behemoth called IE11 that supports Set/Map, but in a very stripped down form of just add, remove and forEach traversal.
It turned out such a crutch:

// modern browsers
if (points.values) {
  return points.values().next();
}
// IE11
else {
  let el;
  points.forEach(function (p, i) {
    if (i == 0) el = p;
  });
  return el;
}

But maybe there is a better solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kurtov, 2017-05-03
@kurtov

We use this option: if the browser does not support some feature, then a polyfill is connected. We detect features, not the browser. As a result, the in-place code is clean and without conditions, so everything is fast and optimal in modern browsers. Polyfills are not productive, but this is the user's choice - let one suffer.
Specifically for your question. I would add an additional "type" by which to determine the type of the collection. For example, the second parameter, if it is difficult (for example, for promises), then pass the object {type: 'type', collection: 'Set'}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question