For a technical interview I was tasked with implementing a missing algorithm in JavaScript. The interviewer supplied me with some code and 18 failing unit tests that once the algorithm was successfully implemented would pass. I'm sure there is a more efficient way to have solved this problem as I tried a few different approaches during my allotted time. This way is the first way that I got to work, which for the technical test was enough but I'd like to know a better way of solving the problem.
Work out if the cards in a poker hand form a straight. (I've already ordered the hand in ascending order.)
PokerHand.prototype._check_straight_function = function(arr) {
var isStraight = false;
for (var j = i = 4; i >= 0 && j > 1; i--)
if (arr[i].value() - 1 == arr[--j].value()) {
isStraight = true;
} else {
isStraight = false;
}
};
return isStraight;
};
Things I didn't get working that I think might work faster, I'd really appreciate if someone could talk me through a working version of the below approach(es) and help me understand which is the fastest to evaluate.
arr.pop().value - 1 == arr.pop().value()
filter
the array to create a new array that contains only values where the next index (arr[++i])
is the current index + 1 and then see if the new array is the same length.for loop
with a break / continue
to short circuit as soon as the straight ends. A sequence is a set of instructions executed one after the other. A source code is a collection of instructions whose sequence is the order in which it has been written. The processor will then read it in order from beginning to end, executing the code as it goes. Example. <script>
To get the highest or lowest number from an array in JavaScript, you can use the Math. max() or the Math. min() methods then spread the elements from the array to these methods using the spread operator ( ... ).
log(max); var min = numbers. reduce((total, value, index, array) => { if(index === 0) return array[0]; return total < value ? total : value; }); console. log(min);
JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .
There's no need to assign a variable isStraight at all.
PokerHand.prototype._check_straight_function = function(arr) {
for (var i = i = 4; i++) {
if (arr[i].value() - 1 != arr[i-1].value()) {
return false;
}
};
return true;
};
Just throwing it out there, I think this one does it with the least amount of lines (3), whether or not that is "better" is subjective as it is probably less clear
var last = arr.pop().value(), popped;
while ((popped = arr.pop().value()) === --last);
return popped === undefined;
here is another way
var isOrdered=true;
[5,6,8,9].sort(function(a, b) {
(b-a != 1)?isOrdered=false:true;
});
alert(isOrdered);
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With