Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using TypeScript but this example is in plain JavaScript. I have a class rank with a child-class master. I need an ordered collection of unique masters. Here's what I have but it seems a little "kak":

function getMasters() {
    var gms = [];
    _.each(this.ranks, (r) => {
        if (gms[r.master.id])
            return;
        gms[r.master.id] = new ExtendedRank(r.master.id r.master.code, r.master.name);
    });

    return _.without(gms, undefined).sort(this.sort);
}

This is the sort function (which I'm relatively happy with):

function sort(l: ExtendedRank, r: ExtendedRank) {
    return l.sortString.localeCompare(r.sortString);
}
share|improve this question

Here's a more functional solution, which based on your example is what you're looking for. It relies on the uniqueness of object keys. Note it's untested, but the idea should work:

function getMasters() {
  var extended = r => new ExtendedRank(r.master.id r.master.code, r.master.name),
  return Object.values(
    this.ranks.reduce((m,r) => Object.assign(m, {[r.master.id]: extended(r)}), {});
  ).sort(this.sort);
}

If you're looking to go even further in this direction, I recommend checking out ramda as a better, more functional alternative to underscore.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.