使用 Ramda 创建对象

Create object with Ramda

我想创建一个可以这样使用的类似函数:

const objectCreator = createObject({
  foo: functionFoo,
  bar: functionBar
})

objectCreator(42) // => { foo: functionFoo(42), bar: functionBar(42) }

所以我的想法是从一组应用于某个值的函数创建一个对象。例如,用例是从一个唯一的对象中提取不同的数据,并将这个函数放在一个管道中。

我可以手动创建这样的函数,但 Ramda(或类似的)中是否已经存在用于此的函数?不知道怎么命名。

Map 可以满足您的大部分需求,前提是您用代码包围它以输入正确的值。例如:

const createObject = specification => value => R.map(f => f(value), specification);

const objectCreator = createObject({
  foo: val => val * 2,
  bar: val => val + 1,
});

let result = objectCreator(42); // { foo: 84, bar: 43 }

或者如果你希望它被咖喱化(这样你就可以同时或分别传入规范和值):

const createObject = R.curry((specification, value) => R.map(f => f(value), specification))

let result = createObject({
  foo: val => val * 2,
  bar: val => val + 1,
}, 42); // { foo: 84, bar: 43 }

编辑:

如果输入的顺序颠倒(即值在前,规格在后),会更简单:

const createObject = value => R.map(f => f(value))

applySpec 这样做:

const functionFoo = x => 'Foo: ' + x;
const functionBar = x => 'Bar: ' + x;

const objectCreator = applySpec({
  foo: functionFoo,
  bar: functionBar
});

objectCreator(42); // {"bar": "Bar: 42", "foo": "Foo: 42"}