// 定义过滤条件对象的类型
type FilterCondition = {
[key: string]: string | number;
};
// 定义操作指令类型
type Operation = 'sort' | 'reverse';
// 定义函数参数类型
type DataProcessorParams = [Record<string, any>, FilterCondition?, ...Operation[]];
// 实现数据处理函数
function dataProcessor(...args: DataProcessorParams): Record<string, any> {
const [baseData, filterCondition = {}, ...operations] = args;
let result: Record<string, any> = {};
// 根据过滤条件筛选属性
for (const key in baseData) {
if (Object.prototype.hasOwnProperty.call(baseData, key) && (filterCondition[key] === undefined || baseData[key] === filterCondition[key])) {
result[key] = baseData[key];
}
}
// 按照操作指令进行操作
operations.forEach(operation => {
if (operation === 'sort') {
const keys = Object.keys(result).sort();
result = keys.reduce((acc, key) => {
acc[key] = result[key];
return acc;
}, {} as Record<string, any>);
} else if (operation === 'reverse') {
const keys = Object.keys(result).reverse();
result = keys.reduce((acc, key) => {
acc[key] = result[key];
return acc;
}, {} as Record<string, any>);
}
});
return result;
}