典型面试题 ,编写满足下列要求的函数
考察点
- javascript基础
- 正则表达式
- 链式调用
// 约定:
// title数据类型为String
// userId为主键,数据类型为Number
var data = [
{userId: 8, title: 'title1'},
{userId: 11, title: 'other'},
{userId: 15, title: null},
{userId: 19, title: 'title2'}
];
var find = function(origin) {
// your code are here...
}
// 查找 data 中,符合条件的数据,并进行排序
var result = find(data).where({
'title': /\d$/
}).orderBy('userId', 'desc');
console.log(result);// [{ userId: 19, title: 'title2'}, { userId: 8, title: 'title1' }];
var find = function(origin){
var result = origin
var Truefind = function(){
this.where = function(reg){
var dataKey = Object.keys(reg)[0]
result = origin.filter((item)=>{
return item[dataKey] && item[dataKey].match(reg[dataKey])
})
return this
}
this.orderBy = function(title, order="desc"){
result.sort((a,b)=>{
return order==="desc" ? b[title] - a[title] : a[title] - b[title]
})
return result;
}
}
var instance = new Truefind()
return instance