admin管理员组

文章数量:1391925

I'd like to create a function similar that would be used this way:

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

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

So the idea is to create an object from a set of function applied to a value. Use case is for example to extract different data from a unique object, and put this function in a pipe.

I could create such a function manually, but isn't there already an existing function in Ramda (or similar) for this? I can't figure how it could be named.

I'd like to create a function similar that would be used this way:

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

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

So the idea is to create an object from a set of function applied to a value. Use case is for example to extract different data from a unique object, and put this function in a pipe.

I could create such a function manually, but isn't there already an existing function in Ramda (or similar) for this? I can't figure how it could be named.

Share Improve this question asked Jun 28, 2018 at 18:32 Eric BurelEric Burel 5,0066 gold badges42 silver badges67 bronze badges 1
  • 1 Don't think there's any single function in Ramda that does this. – Jared Smith Commented Jun 28, 2018 at 18:51
Add a ment  | 

2 Answers 2

Reset to default 4

applySpec does that:

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"}

Map does most of what you need, provided you surround it with code to feed the right values in. For example:

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 }

Or if you want it to be curried (so you can pass in the specification and the value at the same time, or separately):

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 }

EDIT:

If the order of the inputs was reversed (ie, value first, specification later), it would be simpler:

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

本文标签: javascriptCreate object with RamdaStack Overflow