1. 实现一个简单的模板渲染,给定一个模板和一个对象,利用对象中的数据生成模板字符串,并返回最终结果。
function renderTpl(tpl, data) {
}
let tpl = '你好,我们公司是{company},我们部门是{bu}';
let tplData = {
company: '阿里巴巴',
bu: '天猫精灵'
}
const str = renderTpl(tpl, tplData);
console.log(str);
解题:
function renderTpl(tpl, data) {
Object.keys(data).forEach((k) => {
tpl = tpl.replace(`{${k}}`, data[k]);
});
return tpl;
}
let tpl = "你好,我们公司是{company},我们部门是{bu}";
let tplData = {
company: "阿里巴巴",
bu: "天猫精灵",
};
const str = renderTpl(tpl, tplData);
console.log(str);
2. 实现find函数,使得下面的方法调用正确
const data = [
{userId: 8, title: 'title1'},
{userId: 11, title: 'other'},
{userId: 15, title: null},
{userId: 19, title: 'title2'}
];
const find = function(origin) {
}
const result = find(data).where({
'title': /\d$/
}).orderBy('userId', 'desc');
const result1 = find(data).orderBy('userId', 'asc').where({
'title': /\d$/
})
console.log(result);
console.log(result1);
解题:
const data = [
{ userId: 8, title: "title1" },
{ userId: 11, title: "other" },
{ userId: 15, title: null },
{ userId: 19, title: "title2" },
];
const find = function (origin) {
let obj = new Object(origin);
Object.defineProperty(obj, "where", {
configurable: false,
enumerable: false,
writable: false,
value: function (where) {
for (let key in where) {
if (where.hasOwnProperty(key)) {
obj = obj.filter((v) => where[key].test(v[key]));
}
return find(obj);
}
},
});
Object.defineProperty(obj, "orderBy", {
configurable: false,
enumerable: false,
writable: false,
value: function (key, order) {
obj.sort((a, b) => {
if (order == "desc") {
return b[key] - a[key];
} else {
return a[key] - b[key];
}
});
return find(obj);
},
});
return obj;
};
const result = find(data)
.where({
title: /\d$/,
})
.orderBy("userId", "desc");
const result1 = find(data).orderBy("userId", "asc").where({
title: /\d$/,
});
console.log(result);
console.log(result1);