It's fine to separate the sorting into its own function if you want. But you need to give the suits sorting function a different name, otherwise it isn't accessible from within isFlush, as there's already a local suits variable in there. And also you need to actually call the function in order to sort the data.
Try this:
'use strict';
const toSuit1 = (card) => card.charAt(card.length - 1); //only color
const sortSuits = (hand) => hand.map(toSuit1).sort();
const isFlush = (suits) => {
suits = sortSuits(suits);
return suits[0] === suits[4] ? 'true' : 'false';
}
console.log(isFlush(['7H', '2H', 'QH', '10H', '5H'])); // true
console.log(isFlush(['7H', '2H', 'QX', '10H', '5H'])); // false
However since your stated goal is "shortening" the code, it's debatable whether this is really the shortest version. If the sorting function doesn't need to be a separate function (in order to make it re-usable, for example), then you can save a line of code by re-integrating it back into the isFlush function, and just using the shortened ternary syntax instead of the if in the original:
'use strict';
const toSuit1 = (card) => card.charAt(card.length - 1); //only color
const isFlush = (suits) => {
suits = suits.map(toSuit1).sort();
return suits[0] === suits[4] ? 'true' : 'false';
}
console.log(isFlush(['7H', '2H', 'QH', '10H', '5H'])); // true
console.log(isFlush(['7H', '2H', 'QX', '10H', '5H'])); // false
And we could take that one step further, if the toSuit1 function also isn't re-used, then again it can be simply integrated into the sorting process directly:
'use strict';
const isFlush = (suits) => {
suits = suits.map((card) => card.charAt(card.length - 1)).sort();
return suits[0] === suits[4] ? 'true' : 'false';
}
console.log(isFlush(['7H', '2H', 'QH', '10H', '5H'])); // true
console.log(isFlush(['7H', '2H', 'QX', '10H', '5H'])); // false
As you can see from this example though, "shortening" the code can come at the cost of re-usability, and readability, and the ability to independently test different aspects of the functionality. I would question whether "shorter code" should really be a target in itself. You need to strike an appropriate balance between verbosity the other factors I mentioned, rather than having a simplistic plan to make everything shorter.
suitsfunction. Furthermore, you shadow it with the parameter ofisFlush, so you cannot call it.suits; you can check whether the hand is a flush by doing:const isFlush = (hand) => !hand.some(card => toSuit1(card) !== toSuit1(hand[0])). In other words you check whether there is at least one card whose color is different from the one of the first cardconst isFlush = (suits) => { suits = sortSuits(suits); return suits[0] === suits[4]; }