简体   繁体   中英

Using function within Node.js module

I'm having trouble using a function within a Node.js module. I'm using a custom sort function to sort an array of objects by the value of a certain property.

exports.getResult = function(cards) {
    cards.sort(sortByField('suit'));
    ...
    ...
    ...
    return cards;
}

function sortByField(fieldName) {
    return function(card1, card2) {
        return card1[fieldName] < card2[fieldName]
    };
}

When I use the getResult function NOT as an export, and call it from the same file, everything works as expected. The card object with the highest suit value is first and the card object with the lowest value is last.

However, when I call the function as an export from my index.js, the sort doesn't happen. There is no error, the rest of the function just executes with the array in the same order that it was before the sort function.

I've tried everything I can think of. I've done module.exports.sortByField(), I've tried requiring the .sortByField() in a completely separate module. I'm sure there's a simple answer, but I just can't figure it out.

I suspect that it's working the same in both cases, but the problem is that the sort callback is incorrect.

A sort callback must return a negative number, 0, or a positive number, not a boolean: A negative number if the first entry should be before the second, 0 if they're the same, a positive number if the first should come after the second.

If cards contains numbers, you want:

return card1[fieldName] - card2[fieldName];

...if you want to sort ascending.

If it's strings, you can use localeCompare :

return card1[fieldName].localeCompare(card1[fieldName]);

So I hope I can be forgiven for being new to all this, but it turns out that the code I posted originally wasn't the problem at all. Long story short, the array that I passed to the getResult() function was an array of arrays, instead of an array of objects.

I was adding cards to an array of played cards with this code:

playedCards.push(game.playCard(1, players[0].hand, 3));

and the playCard() function was exporting an array:

exports.playCard = function(amount, hand, index) {
    const cards = hand.splice(index, amount);
    return cards;
};

but I should have been exporting an individual object:

exports.playCard = function(amount, hand, index) {
    const cards = hand.splice(index, amount);
    return cards[0];
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM