Giter VIP home page Giter VIP logo

Comments (7)

ZHAISHENKING avatar ZHAISHENKING commented on August 23, 2024 1

译文一

  function tree(list) {
      let newList = list.filter((item) => item.parentCode === '');
      ((item) => {
         item.forEach(element => {
            element.children = [];
            element.children.push(list.filter(item => item.parentCode === element.code));
         });
      })(newList);
      return newList;
  }

   tree(list);

这样写有问题,首先只能解决一层嵌套,‘五道口’第二层嵌套就拿不到了。 其次,list.filter返回的是数组,push数组得到的是[[]]的形式。在你的基础上改了一下:

  function tree(list){
    const firstArray = list.filter(o=>{if(o.parentCode=='') return o})
    const func = (arr) => {
        arr.map(o=>{
            let children = []
            list.forEach((e)=>{
                if(e.parentCode === o.code){
                    children.push(e)
                    func(children)
                }
            })
            if(children.length) o.children = children
        })
        return arr
    }
    return func(firstArray)
  }

from frontend-interview.

chaooo avatar chaooo commented on August 23, 2024

题目1: (比较笨的方法。)

function tree(list) {
    let temp = [];
    let base = list.map(item => {
        item.children = [];
        return item;
    });
    if (base.length > 0) {
        for (let i = 0; i < base.length; i++) {
            if (base[i].parentCode === '') {
                temp.push(base[i]);
                base.splice(i, 1);
            }
        }
        if (base.length > 0) {
            for (let j = 0; j < temp.length; j++) {
                for (let k = 0; k < base.length; k++) {
                    if (base[k].parentCode === temp[j].code) {
                        temp[j].children.push(base[k]);
                        base.splice(k, 1);
                    }
                }
            }
            if (base.length > 0) {
                for (let l = 0; l < temp.length; l++) {
                    if (temp[l].children.length > 0) {
                        for (let m = 0; m < temp[l].children.length; m++) {
                            for (let n = 0; n < base.length; n++) {
                                if (base[n].parentCode === temp[l].children[m].code) {
                                    temp[l].children[m].children.push(base[n]);
                                    base.splice(n, 1);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return temp;
}

from frontend-interview.

evilrescuer avatar evilrescuer commented on August 23, 2024

题目1-解答:

function tree(list) {
    // {
    //     1001: {},
    //     10011: {},
    //     100111: {},
    //     ...
    // }
    this.flatNodeMapping = {}

    // {
    //     1001: {
    //        10011: {
    //             100111: {}
    //        }
    //     },
    //     ...
    //  }
    this.treeCodeMapping = {}

    list.forEach(item => this.flatNodeMapping[item.code] = item)
    list.forEach(item => {
        (function(eachItem) {
            let destItem = {...eachItem}
            const parentCodePath = [destItem.code]
            while(destItem.parentCode) {
                parentCodePath.push(destItem.parentCode)
                destItem = flatNodeMapping[destItem.parentCode]
            }
            parentCodePath.reverse()
            setInnerProperty(this.treeCodeMapping, parentCodePath, {})
        })(item)
    })

    return transformTreeCodeMappingToNodeTree(this.treeCodeMapping, this.flatNodeMapping)
}

function setInnerProperty(mapping, proArr, value) {
    const property = proArr.shift()
    const obj = mapping[property]
    if(proArr.length === 0) {
        mapping[property] = value
        return
    }
    setInnerProperty(obj, proArr, value)
}

function transformTreeCodeMappingToNodeTree(treeCodeMapping, flatNodeMapping) {
    let arr = []
    for(let field in treeCodeMapping) {
        const value = treeCodeMapping[field]
        let children = []
        if(Object.keys(value).length > 0) children = transformTreeCodeMappingToNodeTree(value, flatNodeMapping)
        arr.push({
            ...flatNodeMapping[field],
            children,
        })
    }
    return arr
}

from frontend-interview.

evilrescuer avatar evilrescuer commented on August 23, 2024

题目2-解答:

function $(selector) {
    const jq = new jQuery()
    jq.init(selector)
    return jq
}
function jQuery() {}
jQuery.prototype = {
    init: function (selector) {
        let nodes = document.querySelectorAll(selector)
        nodes.forEach((node, index) => this[index] = node)
        this.length = nodes.length
    },

    addClass: function (cls) {
        for(let i=0; i<this.length; i++) {
            const className = this[i].className
            if(className.indexOf(cls) !== -1) continue
            this[i].className = className ? `${className} ${cls}` : cls
        }
    }
}

$.get = function (url, data) {
    const xhr = new XMLHttpRequest()
    let responseData = null

    let doneCb = null
    let failCb = null
    let alwaysCb = null

    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            if(xhr.status === 200) {
                responseData = xhr.responseText
                doneCb && doneCb(responseData)
                alwaysCb && alwaysCb(responseData)
            }
            else {
                failCb && failCb()
                alwaysCb && alwaysCb()
            }
        }
    }
    xhr.open('GET', `${url}${objectToURLStr(data)}`)
    xhr.send()

    function done(cb) {
        doneCb = cb
        return this
    }

    function fail(cb) {
        failCb = cb
        return this
    }

    function always(cb) {
        alwaysCb = cb
        return this
    }

    return {
        done,
        fail,
        always
    }
}

function objectToURLStr(obj) {
    let str = ''
    for(let field in obj) {
        const splitStr = str ? '&' : '?'
        str = `${str}${splitStr}${field}=${obj[field]}`
    }
    return str
}

$('p').addClass('ok')
$.get('http://api.jirengu.com/getWeather.php', {
        city: '北京'
    })
    .done(data => console.log(data))
    .fail(() => console.log('get data error'))
    .always(() => console.log('always'))

from frontend-interview.

dwanl avatar dwanl commented on August 23, 2024

题目一

  function tree(list) {
      let newList = list.filter((item) => item.parentCode === '');
      ((item) => {
         item.forEach(element => {
            element.children = [];
            element.children.push(list.filter(item => item.parentCode === element.code));
         });
      })(newList);
      return newList;
  }

   tree(list);

from frontend-interview.

fengyk1 avatar fengyk1 commented on August 23, 2024

题一

  function transform(obj, children) {
    children.forEach((item) => {
      if (obj.code === item.parentCode) {
        (obj.children = obj.children || []).push(transform(item, children));
      }
    });
    return obj;
  }
  return list
    .filter((item) => !item.parentCode)
    .map((item) => transform(item, list));
}

from frontend-interview.

ainuo5213 avatar ainuo5213 commented on August 23, 2024
function tree(array) {
    const result = array.filter(r => r.parentCode === '');
    (function loop(rootNodes) {
        for (const rootNode of rootNodes) {
            rootNode.children = array.filter(r => r.parentCode === rootNode.code);
            if (rootNode.children.length) {
                loop(rootNode.children);
            }
        }
    })(result);
    return result;
}

from frontend-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.