Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jrg interview questions #42

Open
jirengu opened this issue Mar 18, 2019 · 7 comments
Open

jrg interview questions #42

jirengu opened this issue Mar 18, 2019 · 7 comments

Comments

@jirengu
Copy link
Owner

jirengu commented Mar 18, 2019

题目1

写一个函数tree,实现如下功能

function tree(list) {
  //todo...
}

let list = [
  {
    code: '1001',
    parentCode: '',
    name: '北京'
  },
  {
    code: '10011',
    parentCode: '1001',
    name: '海淀'
  },
  {
    code: '10012',
    parentCode: '1001',
    name: '大兴'
  },
  {
    code: '100112',
    parentCode: '10011',
    name: '五道口'
  },
  {
    code: '1002',
    parentCode: '',
    name: '上海'
  },
  {
    code: '10022',
    parentCode: '1002',
    name: '徐汇'
  },
  {
    code: '1003',
    parentCode: '',
    name: '武汉'
  }

]


let newList = tree(list)
console.log(newList)

/*
[
  {
    code: '1001',
    parentCode: '',
    name: '北京',
    children: [
      {
        code: '10011',
        parentCode: '1001',
        name: '海淀',
        children: [
          {
            code: '100112',
            parentCode: '10011',
            name: '五道口',
            children: []
          }
        ]
      },
      {
        code: '10012',
        parentCode: '1001',
        name: '大兴',
        children: []
      }
    ]
  },
  {
    code: '1002',
    parentCode: '',
    name: '上海',
    children: [
      {
        code: '10022',
        parentCode: '1002',
        name: '徐汇',
        children: []
      }
    ]
  },
  {
    code: '1003',
    parentCode: '',
    name: '武汉',
    children: []
  }

]

*/

题目2

补充如下代码实现一个简单的jQuery

function $(selector) {
  //todo..
}
$.prototype = {
  init: function(selector) {
    let nodes = document.querySelectorAll(selector)
    nodes.forEach((node, index) => this[index] = node)
    this.length = nodes.length    
  },
  
  addClass: function(cls) {
    // todo...
  }
}
//todo ...

$.get = function(url, data) {
    function done() { 
       //todo... 
    }
    function fail() {
      //todo...
    }
    function always() {
       //todo...
    }
  
    return { done, fail, always }
  }



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

chaooo commented Apr 3, 2019

题目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;
}

@evilrescuer
Copy link

evilrescuer commented Jul 23, 2019

题目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
}

@evilrescuer
Copy link

题目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'))

@dwanl
Copy link

dwanl commented Aug 27, 2019

题目一

  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);

@ZHAISHENKING
Copy link

ZHAISHENKING commented Dec 4, 2019

译文一

  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)
  }

@fengyk1
Copy link

fengyk1 commented Oct 11, 2021

题一

  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));
}

@ainuo5213
Copy link

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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants