2020年5月28日 星期四

project 對 dom.tree 先廣域搜索指定的節點,再排序

const getCommentLis = {
            main(root) {
                let commentList = [];

                let dataList = [{
                    level: [1],
                    node: root
                }];

                // 位數
                let digit = dataList[0].level.length;

                let i = 0;
                let data;
                while (null != (data = dataList[i++])) {
                    // debugger;

                    const level = data.level;
                    const node = data.node;

                    if (node.tagName != null) {
                        node.childNodes.forEach((child, i) => {
                            let _level = level.slice()
                            _level.push(i + 1);

                            if (_level.length > digit) {
                                digit = _level.length;
                            }

                            dataList.push({
                                level: _level,
                                node: child
                            });
                        });
                    } else {
                        if (node.nodeType == 8) {
                            let parent = node.parentNode;
                            commentList.push({
                                parent: parent,
                                node: node,
                                level
                            });
                        }
                    }
                } // endWhile
                // debugger;
                console.dir(commentList);

                commentList.sort((a, b) => {
                    if (Array.isArray(a.level)) {
                        a.level = this.getLevel(digit, a.level);
                    }

                    if (Array.isArray(b.level)) {
                        b.level = this.getLevel(digit, b.level);
                    }

                    return (a.level - b.level);
                });

                console.dir(commentList);
                return commentList;
            },
            getLevel(digit, level) {
                debugger;
                let j = digit - level.length;

                // debugger;
                // 基數
                let p = 1;
                for (let i = 0; i < j; i++) {
                    p *= 10;
                }

                // debugger;
                let res = 0;
                let num;
                while (null != (num = level.pop())) {
                    res = res + num * p;
                    // 十進位
                    p *= 10;
                }

                return res;
            }
        }