Es6 map / set iterate from specific item (back)

Beginner here, I'm a little lost with es6 set , map and generators.

How can I select an item on the map and then effectively draw back from this point? Preferably without going through the whole set / map.

let v = myMap.get('key')

so, from 'v' to the start of the map (back)?

Thank you!

+1
source share
2 answers

You can create a set of iterative helpers, and then create to create the desired effect:

/* iterTo iterates the iterable from the start and up to (inclusive) key is found.
The function "understands" the Map type when comparing keys as well as
any other iterables where the value itself is the key to match. */
function* iterTo(iterable, key) {
  for(let i of iterable) {
    yield i;
    if((iterable instanceof Map && i[0] === key) || i === key)
      return;
  }
}

// Same as iterTo, but starts at the key and goes all the way to the end
function* iterFrom(iterable, key) {
  let found = false;
  for(let i of iterable) {
    if(found = (found || (iterable instanceof Map && i[0] === key) || i === key))
      yield i;
  }
}

// reverseIter creates a reverse facade for iterable
function* reverseIter(iterable) {
  let all = [...iterable];
  for(let i = all.length; i--; )
    yield all[i];
}

Then you can use and compose like this:

let m = new Map();
m.set(1, 'a');
m.set(2, 'b');
m.set(3, 'c');
m.set(4, 'd');
m.set(5, 'e');

let s = new Set();
s.add(100);
s.add(200);
s.add(300);
s.add(400);


console.log(...iterTo(m, 3), ...iterFrom(m, 3));
console.log(...reverseIter(iterTo(m, 3)), ...reverseIter(iterFrom(m, 3)));

console.log(...reverseIter(iterTo(s, 200)));
+2
source

, , , , - slice keys key, , .

, map :

let keys = Object.keys(map);
return keys.slice(0, keys.indexOf('key')).map((k) => map[k]);

.

+1

All Articles