笔试题集

笔试场上,刀刀致命

1

//1. 给定一个模板和一个对象,利用对象中的数据渲染模板,并返回最终结果。
let template = '你好,我们公司是{{ company }},我们属于{{group.name}}业务线,我们在招聘各种方向的人才,包括{{group.jobs[0]}}、{{group["jobs"][1]}}等。'
function render (template, obj) {}
let obj = {
  group: {
    name: 'MI',
    jobs: ['前端']
  },
  company: 'BAT'
}

解答:
借助evalmatchAll,借助eval动态执行代码:

function render (template, obj) {
// 代码实现
  const re = /\{\{\s*(.+?)\s*\}\}/g
  let results = template.matchAll(re)
  for (let match of results) {
    with (obj) {
      template = template.replace(match[0], eval(match[1]))
    }
  }
  return template
}

或者借助Function构造函数动态执行代码:

function render (template, obj) {
// 代码实现
  const re = /\{\{\s*(.+?)\s*\}\}/g
  return template.replace(re, function(match, $1) {
     let val = (new Function(`return this.${$1}`)).call(obj)
     return val
  })
}

2

// 2. 完成 convert(list) 函数,实现将 list 转为 tree
/**
 * @param list {object[]}, 
 * @param parentKey {string}
 * @param currentKey {string}
 * @param rootValue {any}
 * @return object
 */
convert(list, 'parentId', 'id', 0)
const list = [
  {
    'id': 19,
    'parentId': 0
  },
  {
    'id': 18,
    'parentId': 16
  },
  {
    'id': 17,
    'parentId': 16
  },
  {
    'id': 16,
    'parentId': 0
  }
]

解答:

function convert(list, parentKey, currentKey, rootValue) {
  const tree = {[currentKey]: rootValue}
  // 获取某一父节点的子节点
  function getChildren(leaf, pid) {
    let len = list.length
    for (let i = 0; i < len; i++) {
      let item = list[i]
      if (!item) continue
      if (item[parentKey] === pid) {
        if (leaf.children) {
          leaf.children.push(item)
        } else {
          leaf.children = [item]
        }
        list[i] = null
      }
    }
    if (list.some(item => item) && leaf.children) {
      for (let child of leaf.children) {
        getChildren(child, child.id)
      }
    }
    return leaf
  }
  return getChildren(tree, rootValue)
}

思路:先写一个通用的获取子节点的函数,然后递归调用。缺点,有副作用,会改变传入的list参数。

3

对数字的“重量”排序。如 ‘15’的重量是1+5=6。重量相同时,按字典序排序。
'15 1 9 26' => '1 15 26 9'

猜你喜欢

转载自www.cnblogs.com/imgss/p/12158946.html