Skip to content

Instantly share code, notes, and snippets.

@vorg
Created October 6, 2014 16:53
Show Gist options
  • Save vorg/d362361011b4d6c733c1 to your computer and use it in GitHub Desktop.
Save vorg/d362361011b4d6c733c1 to your computer and use it in GitHub Desktop.
Mapping edges to vertices with ramda
var R = require('ramda');
var list = ['a', 'b', 'c'];
var edges = [[0, 1], [1,2]];
var values;
//1
values = edges.map(function(edge) {
return [ list[edge[0]], list[edge[1]] ];
});
//2
values = edges.map(function(edge) {
return edge.map(function(i) { return list[i]; });
});
//3
values = R.map(function(edge) {
return edge.map(function(i) { return list[i] });
}, edges);
//4
values = R.map(function(edge) {
return R.map(R.rPartial(R.prop, list), edge);
}, edges);
//5
values = R.map(R.map(R.rPartial(R.prop, list)), edges);
// Profit!
// a) edge can have many indices and this still works
// b) if list is a property than we can use `this.list` and don't worry as there is no nested functions
// c) we need to change list variable in only one place
// d) there is no edge variable at all
// f) all that stuff is curried so:
var listExtractor = R.map(R.map(R.rPartial(R.prop, list)));
values = listExtractor(edges);
values = listExtractor(anotherEdges);
@buzzdecafe
Copy link

cool! one teensy tweak makes it even shorter, and arguably more readable(?):

var listExtractor = R.map(R.map(R.props(list)));

@CrossEye
Copy link

CrossEye commented Oct 7, 2014

An interesting way to extend this to make a two-argument function would be

var listExtractor = R.useWith(R.map, R.compose(R.map, R.props), R.identity);

Then you can use it like:

listExtractor(list, edges); //=> [['a', 'b'], ['b', 'c']]

or

var makeEdges = listExtractor(list);
makeEdges([[0, 1], [1, 2], [2, 0]]); //=> [['a', 'b'], ['b', 'c'], ['c', 'a']]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment