Created
October 6, 2014 16:53
-
-
Save vorg/d362361011b4d6c733c1 to your computer and use it in GitHub Desktop.
Mapping edges to vertices with ramda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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
cool! one teensy tweak makes it even shorter, and arguably more readable(?):
var listExtractor = R.map(R.map(R.props(list)));