Written field, fatal knife
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'
}
ANSWER:
With eval
and matchAll
, with the eval dynamic code execution:
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
}
Or by Function
constructor dynamic code execution:
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
}
]
answer:
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)
}
Ideas: the first to write a generic function to get the child nodes, then the recursive call. Disadvantages, side effects, will change the parameter passed in list.
3
Digital "weight" for sorting. The weight of '15' is 1+5=6
. By weight of the same, lexicographically sorted.
1926 '15 '=>' 115269 '