I saw this question and wondered how it'd be best to accomplish this using Ramda.
I'm new to the library so I thought it'd be an interesting learning exercise.
I have a working solution but it seems overly complicated and verbose. I'd be grateful for any suggestions on what other ways it would be possible to achieve this output using Ramda.
I'm aware that this doesn't need a library; as I say, I approached it as a learning exercise.
Here's what I have:
const { addIndex, always, fromPairs, join, map, sort, toPairs, unnest } = R;
const song = {
"99": [0, 7],
"bottles": [1, 8],
"of": [2, 9],
"beer": [3, 10],
"on": [4],
"the": [5],
"wall": [6]
};
const toSentence = join(' ');
const parsed = toSentence(
map(
([_, word]) => word,
sort(
([a, _], [b, __]) => a < b ? -1 : 1,
unnest(
map(
([word, indices]) => map(
index => [index, word],
indices,
),
toPairs(song)
)
)
)
)
)
console.dir(parsed)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
sort
and themap
, then the sort doesn't need to do \$n \cdot log(n)\$ array dereferences. Your sort function is unstable and won't preserve the ordering of equal elements. It doesn't matter in this problem; when it does matter, it's a source of nasty, subtle bugs, so always be aware of when you're doing that. \$\endgroup\$