Open qappleh opened 3 years ago
function find (origin) {
return {
where: function (obj) {
let r = []
r = origin.filter(item => {
return item.title !== null && item.title.toString().search(obj.title) > -1
})
return {
orderBy: function (field, orderTyep = 'desc') {
let oo = {}
r.map(o => {
oo[o[field]] = o
})
let result = []
Object.keys(oo).sort((a, b) => orderTyep === 'desc' ? b - a : a - b).forEach(i => { result.push(oo[i]) })
return result
}
}
}
}
}
function find(array) {
return new S(data);
}
function S(data) {
this.data = data;
this.filters = {};
this.orderings = [];
}
S.prototype.where = function (query) {
this.filters = Object.assign(
{},
this.filters,
Object.keys(query).reduce(
// 这里要处理null等特殊值
(a, c) => ((a[c] = (d) => query[c].test(d[c])), a),
{}
)
);
return this;
};
S.prototype.orderBy = function (field, desc = "desc") {
this.orderings.push((a, z) =>
desc == "desc" ? z[field] - a[field] : a[field] - z[field]
);
this.data = this.data.filter((d) =>
Object.keys(this.filters).every((key) => this.filters[key](d))
);
this.orderings.forEach((o) => {
this.data = this.data.sort(o);
});
return this.data;
};
function find(array) {
let data = [...array]
data.__proto__.where = (obj) => {
if (data.length == 0) return []
Object.keys(obj).forEach((key) => {
// 写法不太优雅,待完善
if (!data[0].hasOwnProperty(key)) {
data = []
} else {
data = data.filter((s) => obj[key].test(s[key]))
}
})
return data
}
data.__proto__.orderBy = (key, sortMode) => {
if (data.length == 0 || !data[0].hasOwnProperty(key)) return []
return data.sort((x, y) => {
return sortMode != 'desc' ? x[key] - y[key] : y[key] - x[key]
})
}
return data
}
同时支持了
find(args)
.where()
.where()
.orderBy()