1
\$\begingroup\$

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);
}
\$\endgroup\$
1
\$\begingroup\$

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.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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