-
Notifications
You must be signed in to change notification settings - Fork 97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Day393:请实现 find 函数,使下列的代码调用正确.(蚂蚁金服) #396
Comments
|
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: