我如何以ramda方式创建addGreeting函数?
我尝试创建一个函数,但它不是最佳解决方案。
const animal = {};
const addName = R.assoc('name');
const addGreeting = (transformString) => (animal) => {
return R.assoc('greeting', transformString(animal), animal);
};
const createAnimal =
R.pipe(
addName('Igor'),
addGreeting(animal => `Hello ${animal.name}`),
);
createAnimal(animal);
我希望用ramda编写addGreeting函数。
UPD:我的解决方案
const addName = R.assoc('name');
const addGreeting =
(transformString) =>
R.converge(
R.merge,
[
R.applySpec({
greeting: transformString
}),
R.defaultTo({})
]
)
const createAnimal =
R.pipe(
addName('Igor'),
addGreeting(animal => `Hello ${animal.name}`),
);
createAnimal({});
答案 0 :(得分:1)
您可以使用R.curry
创建addGreeting
和R.applySpec
创建动物创建功能:
const { curry, applySpec, identity } = R
const addGreeting = curry((transformString, name) => transformString(name));
const createAnimal = applySpec({
name: identity,
greeting: addGreeting(name => `Hello ${name}`)
})
console.log(createAnimal('Igor'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>