• 【树结构】构造树结构(优化版)


    function Container()
    {
    this.keySet = [];
    this.entrySet = {};

    this.put = function(key, value)
    {
    this.keySet.push(key);
    this.entrySet[key] = value;
    return this;
    }

    this.get = function(key)
    {
    return this.entrySet[key];
    }

    this.keys = function()
    {
    return this.keySet;
    }

    this.size = function()
    {
    return keySet.length;
    }
    }

    function Region(id, name, pId, level, type)
    {
    this.id = id;
    this.name = name;
    this.pId = pId;
    this.level = level;
    this.type = type;
    this.parent = false;
    this.children = false;
    this.status = false;
    }

    Region.prototype.getId = function()
    {
    return this.id;
    }

    Region.prototype.getName = function()
    {
    return this.name;
    }

    Region.prototype.getPId = function()
    {
    return this.pId;
    }
    Region.prototype.getStatus = function()
    {
    return this.status;
    }
    Region.prototype.setStatus = function(status)
    {
    this.status = status;
    }

    Region.prototype.setParent = function(parent)
    {
    this.parent = parent;
    }

    Region.prototype.getParent = function()
    {
    return this.parent;
    }

    Region.prototype.addChildren = function(child)
    {
    this.children = this.children || [];
    this.children.push(child);
    }

    Region.prototype.getChildren = function()
    {
    return this.children;
    }

    Region.prototype.childOf = function(child)
    {
    if(!this.children || !child || !(child instanceof Region))
    {
    return false;
    }

    for(var i in children)
    {
    if(children[i] == child)
    {
    return true;
    }
    }

    return false;
    }

    var data=othis.option.data; 
    var container = new Container();
    var oldData = eval($(oCheck).val());
    for(var i = 0; i < data.length; i++)
    {
    var item = data[i];
    var region = new Region(item.id, item.name, item.pId, item.level, item.type);
    container.put(item.id, region);
    }

    var keys = container.keys();

    for(var i in keys)
    {
    var region = container.get(keys[i]);
    var pId = region.getPId();

    if(region.level!=1)//pId != 0)
    {
    parentRegion = container.get(pId);
    region.setParent(parentRegion);
    parentRegion.addChildren(region);
    }
    }

    console.log(container);

  • 相关阅读:
    百度面试题
    京东2014年招聘会成都站笔试经历
    把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,不能申请额外的空间
    POJ 2234 Matches Game
    POJ 3903 Stock Exchange
    POJ 2853 Sequence Sum Possibilities
    POJ 3519 Minimal Backgammon
    POJ 2096 Collecting Bugs
    POJ 3071 Football
    HDU 1175 连连看
  • 原文地址:https://www.cnblogs.com/yyumeng/p/8598927.html
Copyright © 2020-2023  润新知