Reputation: 1
Let's say I have a list like
let chain = [ 1, 9, 61, 798 ];
These are essentially denormalized nodes on a route, and I want to add the edges in a database. Ideally I'm looking for something that calls addEdge(node,parent)
for each two elements in the list. I'm looking for the Ramda way of doing this.
Does it bring any unique ability to the mix? I've thought of using something like .reduceRight()
from core javascript,
[ 1, 9, 61, 798 ].reduceRight( (acc,v) => {
addEdge(acc,v);
return v
}, undefined );
But in this case, .reduceRight
is returning something and seems weird to use that in void-context. Is there a better way to do this?
Upvotes: 1
Views: 93
Reputation: 64943
Here's a vanilla JavaScript approach:
const range = (from, to) => {
const output = []
for (let i = from; i < to; i++)
output.push (i)
return output
}
const pairize = xs =>
range (0, xs.length - 1)
.map (i => [xs[i], xs[i + 1]])
const nodes = [1, 9, 61, 798]
const edges = pairize (nodes)
console.log (edges)
Upvotes: 0
Reputation: 6516
You can use R.aperture
to produce a new array containing consecutive elements of a given size.
const nodes = [1, 9, 61, 798]
const edges = R.aperture(2, nodes)
console.log(edges) //=> [[1, 9], [9, 61], [61, 798]]
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
You can then either map
or forEach
over the resulting array containing the pairs of nodes.
Upvotes: 3