想象中的代码和问题在这里:
function makeCreator(obj) {
return (...args) => {
return {
type: obj.type,
...obj.keys: ...args,
// the above is invalid js code, but I'd like
// the keys and values to be automatically paired
///////////////////////////////////////////////////////
// Question: how to make it work using spread operator only?
// I mean, is it possible to do everything with "just "the spread operator?
///////////////////////////////////////////////////////
};
}
}
示例输入
const obj1 = {
type: 'something',
key1: 10,
key2: 20
};
示例输出
const generatedForObj = makeCreator(obj1);
// it should equivalents to
function generatedForObj(v1, v2) {
return {
type: 'something',
key1: v1,
key2: v2,
};
}
// use it like this
const result = generatedForObj (100, 200);
// result is { type: 'something', key1: 100, key2: 200 }
实际上,如果这些信息有帮助,我正在尝试实现某种 redux 的动作创建者。
还提供(应该)工作版本,但我想尝试传播运算符:
function makeCreator(obj) {
return (...args) => {
let { type: obj.type, ...exceptType } = obj;
Object.keys(exceptType).forEach((key, index) => {
exceptType[key] = args[index];
});
return {
type: obj.type,
...exceptType,
};
}
}