I am writing a function that will sort an array of objects either by property or method value. The following code is working. But how do I improve it? I feel there is a lot of duplicate code in it.
transform(array: any, field: string): any[] {
if (!Array.isArray(array)) {
return;
}
array.sort((a: any, b: any) => {
if (typeof a[field] == 'function' && typeof b[field] == 'function') {
if (a[field]() < b[field]()) {
return -1;
} else if (a[field]() > b[field]()) {
return 1;
} else {
return 0;
}
}
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
const callOrTake = it => typeof it === "function" ? it() : it;
const compare = (a, b) => a === b ? 0 : (a > b ? 1 : -1);
const transform = <T> (array: T[], field: keyof T) => array.sort((a, b) => compare(callOrTake(a[field]), callOrTake(b[field])));
The following improvements were made:
(1) Calling the field if it is a function was moved to it's own function to avoid repetition.
(2) The signature of transform was improved so that field cannot be any string, but has to be a key of whatever is inside the array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.