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
2 Answers
Reset to default 4applySpec 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
版权声明:本文标题:javascript - Create object with Ramda - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744721977a2621747.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论