遍历/递归神器tree-crawl简单介绍

项目中再一次遇到一个需求,需要遍历一个树形数据结构里的某一个节点,然后删除。感觉类似的逻辑已经写过n的n次方次了。所以这次打算封装一个通用场景下,对树形数据结构的遍历函数。本着封装新功能前,先去github上搜刮的原则,我找到了本文的猪脚 tree-crawl。

项目名称 tree-crawl
项目地址 https://github.com/ngryman/tree-crawl
cnpm地址 https://npm.taobao.org/package/tree-crawl
npm地址 https://www.npmjs.com/package/tree-crawl

之所以要提供npm地址,是由于github上的项目本人编译了好几次,都没有成功的找到dist目录。所以源文件需要通过 npm i tree-crawl然后去/dist目录里去找。


  • 附官网api
import crawl from 'tree-crawl'

// traverse the tree in pre-order
crawl(tree, console.log)
crawl(tree, console.log, { order: 'pre' })

// traverse the tree in post-order
crawl(tree, console.log, { order: 'post' })

// traverse the tree using `childNodes` as the children key
crawl(tree, console.log, { getChildren: node => node.childNodes })

// skip a node and its children
crawl(tree, (node, context) => {
  if ('foo' === node.type) {
    context.skip()
  }
})

// stop the walk
crawl(tree, (node, context) => {
  if ('foo' === node.type) {
    context.break()
  }
})

// remove a node
crawl(tree, (node, context) => {
  if ('foo' === node.type) {
    context.parent.children.splice(context.index, 1)
    context.remove()
  }
})

// replace a node
crawl(tree, (node, context) => {
  if ('foo' === node.type) {
    const node = {
      type: 'new node',
      children: [
        { type: 'new leaf' }
      ]
    }
    context.parent.children[context.index] = node
    context.replace(node)
  }
})

//发现提供的官方/dist在webpack项目下会import失败,没办法,贴源码

function Context(flags, cursor) {
    this.flags = flags;
    this.cursor = cursor;
}
Context.prototype = {
    skip: function skip() {
        this.flags.skip = true;
    },
    break: function _break() {
        this.flags.break = true;
    },
    remove: function remove() {
        this.flags.remove = true;
    },
    replace: function replace(node) {
        this.flags.replace = node;
    },
    get parent() {
        return this.cursor.parent;
    },
    get depth() {
        return this.cursor.depth;
    },
    get level() {
        return this.cursor.depth + 1;
    },
    get index() {
        return this.cursor.index;
    }
};
function ContextFactory(flags, cursor) {
    return new Context(flags, cursor);
}

function Stack(initial) {
    this.xs = [initial];
    this.top = 0;
}
Stack.prototype = {
    push: function push(x) {
        this.top++;
        if (this.top < this.xs.length) {
            this.xs[this.top] = x;
        } else {
            this.xs.push(x);
        }
    },
    pushArrayReverse: function pushArrayReverse(xs) {
        for (var i = xs.length - 1; i >= 0; i--) {
            this.push(xs[i]);
        }
    },
    pop: function pop() {
        var x = this.peek();
        this.top--;
        return x;
    },
    peek: function peek() {
        return this.xs[this.top];
    },
    isEmpty: function isEmpty() {
        return -1 === this.top;
    }
};
function QueueFactory(initial) {
    return new Stack(initial);
}

function DfsCursor() {
    this.depth = 0;
    this.stack = QueueFactory({ node: null, index: -1 });
}
DfsCursor.prototype = {
    moveDown: function moveDown(node) {
        this.depth++;
        this.stack.push({ node: node, index: 0 });
    },
    moveUp: function moveUp() {
        this.depth--;
        this.stack.pop();
    },
    moveNext: function moveNext() {
        this.stack.peek().index++;
    },
    get parent() {
        return this.stack.peek().node;
    },
    get index() {
        return this.stack.peek().index;
    }
};
function CursorFactory() {
    return new DfsCursor();
}

function Flags() {
    this.break = false;
    this.skip = false;
    this.remove = false;
    this.replace = null;
}
Flags.prototype = {
    reset: function reset() {
        this.break = false;
        this.skip = false;
        this.remove = false;
        this.replace = null;
    }
};
function FlagsFactory() {
    return new Flags();
}

function isNotEmpty(xs) {
    return xs && 0 !== xs.length;
}

function dfsPre(root, iteratee, getChildren) {
    var flags = FlagsFactory();
    var cursor = CursorFactory();
    var context = ContextFactory(flags, cursor);
    var stack = QueueFactory(root);
    var dummy = Object.assign({}, root);
    while (!stack.isEmpty()) {
        var node = stack.pop();
        if (node === dummy) {
            cursor.moveUp();
            continue;
        }
        flags.reset();
        iteratee(node, context);
        if (flags.break) break;
        if (flags.remove) continue;
        cursor.moveNext();
        if (!flags.skip) {
            if (flags.replace) {
                node = flags.replace;
            }
            var children = getChildren(node);
            if (isNotEmpty(children)) {
                stack.push(dummy);
                stack.pushArrayReverse(children);
                cursor.moveDown(node);
            }
        }
    }
}

function dfsPost(root, iteratee, getChildren) {
    var flags = FlagsFactory();
    var cursor = CursorFactory();
    var context = ContextFactory(flags, cursor);
    var stack = QueueFactory(root);
    var ancestors = QueueFactory(null);
    while (!stack.isEmpty()) {
        var node = stack.peek();
        var parent = ancestors.peek();
        var children = getChildren(node);
        flags.reset();
        if (node === parent || !isNotEmpty(children)) {
            if (node === parent) {
                ancestors.pop();
                cursor.moveUp();
            }
            stack.pop();
            iteratee(node, context);
            if (flags.break) break;
            if (flags.remove) continue;
            cursor.moveNext();
        } else {
            ancestors.push(node);
            cursor.moveDown(node);
            stack.pushArrayReverse(children);
        }
    }
}

var THRESHOLD = 32768;
function Queue(initial) {
    this.xs = [initial];
    this.top = 0;
    this.maxLength = 0;
}
Queue.prototype = {
    enqueue: function enqueue(x) {
        this.xs.push(x);
    },
    enqueueMultiple: function enqueueMultiple(xs) {
        for (var i = 0, len = xs.length; i < len; i++) {
            this.enqueue(xs[i]);
        }
    },
    dequeue: function dequeue() {
        var x = this.peek();
        this.top++;
        if (this.top === THRESHOLD) {
            this.xs = this.xs.slice(this.top);
            this.top = 0;
        }
        return x;
    },
    peek: function peek() {
        return this.xs[this.top];
    },
    isEmpty: function isEmpty() {
        return this.top === this.xs.length;
    }
};
function QueueFactory$1(initial) {
    return new Queue(initial);
}

function BfsCursor() {
    this.depth = 0;
    this.index = -1;
    this.queue = QueueFactory$1({ node: null, arity: 1 });
    this.levelNodes = 1;
    this.nextLevelNodes = 0;
}
BfsCursor.prototype = {
    store: function store(node, arity) {
        this.queue.enqueue({ node: node, arity: arity });
        this.nextLevelNodes += arity;
    },
    moveNext: function moveNext() {
        this.index++;
    },
    moveForward: function moveForward() {
        this.queue.peek().arity--;
        this.levelNodes--;
        if (0 === this.queue.peek().arity) {
            this.index = 0;
            this.queue.dequeue();
        }
        if (0 === this.levelNodes) {
            this.depth++;
            this.levelNodes = this.nextLevelNodes;
            this.nextLevelNodes = 0;
        }
    },
    get parent() {
        return this.queue.peek().node;
    }
};
function CursorFactory$1() {
    return new BfsCursor();
}

function bfs(root, iteratee, getChildren) {
    var flags = FlagsFactory();
    var cursor = CursorFactory$1();
    var context = ContextFactory(flags, cursor);
    var queue = QueueFactory$1(root);
    while (!queue.isEmpty()) {
        var node = queue.dequeue();
        flags.reset();
        iteratee(node, context);
        if (flags.break) break;
        if (!flags.remove) {
            cursor.moveNext();
            if (flags.replace) {
                node = flags.replace;
            }
            if (!flags.skip) {
                var children = getChildren(node);
                if (isNotEmpty(children)) {
                    queue.enqueueMultiple(children);
                    cursor.store(node, children.length);
                }
            }
        }
        cursor.moveForward();
    }
}

var defaultGetChildren = function defaultGetChildren(node) {
    return node.children;
};
function crawl(root, iteratee, options) {
    if (null == root) return;
    options = options || {};
    var order = options.order || 'pre';
    var getChildren = options.getChildren || defaultGetChildren;
    if ('pre' === order) {
        dfsPre(root, iteratee, getChildren);
    } else if ('post' === order) {
        dfsPost(root, iteratee, getChildren);
    } else if ('bfs' === order) {
        bfs(root, iteratee, getChildren);
    }
}

export default crawl;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 228,505评论 6 533
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,556评论 3 418
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 176,463评论 0 376
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,009评论 1 312
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,778评论 6 410
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,218评论 1 324
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,281评论 3 441
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,436评论 0 288
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,969评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,795评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,993评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,537评论 5 359
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,229评论 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,659评论 0 26
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,917评论 1 286
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,687评论 3 392
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,990评论 2 374

推荐阅读更多精彩内容