yield*運用

選自阮一峯大神書籍 ECMAScript 6 入門node

運用一:中序遍歷徹底二叉樹

定義Treees6

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']]]);
複製代碼

遍歷二叉樹ui

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()方法實現this

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接口,進行遍歷的。spa

相關文章
相關標籤/搜索