选自阮一峰大神书籍 ECMAScript 6 入门
运用一:中序遍历完全二叉树
定义
Tree类
class Tree {
constructor (left, label, right) {
this.left = left;
this.label = label;
this.right = right;
}
}
遍历中序函数
function* inorder(tree) {
if (tree) {
yield* inorder(tree.left);
yield tree.label;
yield* inorder(tree.right);
}
}
生成二叉树
function make(array) {
return array.length == 1 ?
new Tree(null, array[0], null) :
new Tree(make(array[0]), array[1], make(array[2]));
}
let tree = make([[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]]);
遍历二叉树
let result = [];
for (let node of inorder(tree)) {
result.push(node);
}
// ["a", "b", "c", "d", "e", "f", "g"]
运用二:平铺深度嵌套的数组
function* iterateNestedArray(tree) {
if (Array.isArray(tree)) {
for(let array of tree) {
yield* iterateNestedArray(array);
}
} else yield tree;
}
// test
let tree = [[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]];
[...iterateNestedArray(tree)];
// ["a", "b", "c", "d", "e", "f", "g"]
还可运用Array.prototype.flat()方法实现
let tree = [[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]];
tree = tree.flat(Infinity);
// ["a", "b", "c", "d", "e", "f", "g"]
Note:
yield*表达式相当for...of两者均调用了数据部署的Iterator接口,进行遍历的。