Rotate/Shift Dartlang 中的列表?

Rotate/Shift a list in Dartlang?

Dart 中是否有 better/faster 旋转列表的方法?

List<Object> rotate(List<Object> l, int i) {
  i = i % l.length;

  List<Object> x = l.sublist(i);
  x.addAll(l.sublist(0, i));

  return x;
}

可以简化一点

List<Object> rotate(List<Object> list, int v) {
  if(list == null || list.isEmpty) return list;
  var i = v % list.length;
  return list.sublist(i)..addAll(list.sublist(0, i));
}

如果您想 shift 而不是 rotate,您可以简单地使用 removeAt 函数:

List<int> list = [ 1, 2, 3 ];
int firstElement = list.removeAt(0);
print(list); // [ 2, 3 ]
print(firstElement); // 1

来自文档:

Removes the object at position [index] from this list.

This method reduces the length of this by one and moves all later objects down by one position.

Returns the removed value.

The [index] must be in the range 0 ≤ index < length. The list must be growable.

Here 是一些更有用的 JS 垫片。