const log = console.log;
let find = function (data) {
return {
where(params) {
Object.entries(params).forEach(([key, value]) => {
data = data.filter(item => value.test(item[key]))
});
return this
},
orderBy(key, rule = 'asc') {
function sortBy(key, rule) {
return function (a, b) {
a = a[key];
b = b[key];
if (rule === 'asc') {
return a - b
} else if (rule === 'desc') {
return b - a
}
return 0;
}
}
return data.sort(sortBy(key, rule))
}
}
}
let data = [
{ userId: 8, title: 'title1' },
{ userId: 11, title: 'other3' },
{ userId: 15, title: null },
{ userId: 21, title: 'title2' }
];
let result = find(data).where({
'title': /\d$/,
'userId': /1$/
}).orderBy('userId', 'desc');
console.log(result);// [{ userId: 19, title: 'title2'}, { userId: 8, title: 'title1' }];
console