Given a very simple example:
R.map((a, b) => {
console.log(a, b) // 1, undefined
}, [1, 2, 3])
How can I access the collection as a whole within the map?
A contrived example of using the collection might be:
R.map((item, collection) => {
console.log(item === collection.length)
}, [1, 2, 3])
I could store it in a variable prior, but this is at the end of a chain of functions
R.map
doesn't give you access to the collection inside the mapping function, but you could create a closure around the mapping function in order to give yourself an opportunity to assign a name to the collection.
((collection) => R.map((item) => {
console.log(item === collection.length)
}, collection))([1, 2, 3]);
As the comments have suggested, there are good reasons Ramda does not include this by default. But there is a decorator called addIndex
which adds the index and collection:
const fn = R.addIndex(map)((elt, idx, coll) => elt == coll.length);
fn([1, 2, 3]); //=> [false, false, true]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.