es6 map / set从某个项目(向后)迭代 [英] es6 map/set iterate from certain item (backwards)

查看:113
本文介绍了es6 map / set从某个项目(向后)迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的初学者
我有点迷失es6 设置地图和生成器。

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

如何在地图中选择一个项目,然后从该点向后迭代?最好不经过整个集合/地图。

How can I select an item in a map, then iterate backwards from that point on effectively? Preferably without going through the whole set/map.

let v = myMap.get('key')

所以,从'v'到地图的开头(向后)?

so, from 'v' to the beginning of the map (backwards)?

谢谢!

推荐答案

您可以创建一组迭代帮助器,然后复合以创建所需的效果:

You can create a set of iteration helpers and then compound to create the effect you want:

/* 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];
}

然后,您可以使用和复合如下:

You can then use and compound 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)));

这篇关于es6 map / set从某个项目(向后)迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆