headwinds
headwinds

Reputation: 1851

Can you use the modified value of a underscore chain before its finished?

I'm attempting to create a function that sorts a list of players and identifies the top 5 by score.

I'm running a few chained filters on an array and I'd like to be able to use the current state of the modified array after each step.

I'm currently achieving this in two chain steps but I'd like to it in one if possible:

var hilightTop5 = function( propName, aPlayers ) {

   var aSortedReversed = _.chain(aPlayers)
        .sortBy( function(player){ return player[propName] })
        .reverse()
        .value();

    var aTop5Map = _.chain(aSortedReversed)
        .map( function(player) {  
            player.top5 = ( player[propName] >= aSortedReversed[4][propName] ) ? 0 : 1; 
            return player; })   
        .value();

    return aTop5Map;
};  

I'd like to do something like this and only use one chain:

    var hilightTop5 = function( propName, aPlayers ) {

       var aTop5Map = _.chain(aPlayers)
            .sortBy( function(player){ return player[propName] })
            .reverse()
            .map( function(player) {  
                var aCurrentStateTop5Map = aTop5Map.value(); // this.aTop5Map.value() ?!
                player.top5 = ( player[propName] >= aCurrentStateTop5Map[4][propName] ) ? 0 : 1; 
                return player; })   
            .value();


        return aTop5Map;
    }; 

Is that possible? To somehow use the state of the array after each filter step?

Upvotes: 0

Views: 175

Answers (1)

psquared
psquared

Reputation: 1129

You could use the list value that underscore passes to the map iterator:

var hilightTop5 = function(sortProperty, players) {
    return _.chain(players)
        .sortBy(sortProperty)
        .reverse()
        .map(function(player, key, list) {
            player.top5 = (player[sortProperty] >= list[4][sortProperty]) ? 1 : 0;
            // Another possibility:
            // player.top5 = (key < 5) ? 1 : 0;
            return player;
        })
        .value();            
}

Upvotes: 1

Related Questions