I have a function that returns elements consecutively in a row so for instance, If there are 4 'green' elements consecutively in a row, the Function should return the string: 'Green Wins'
['green', 'blue', 'green', 'green', 'green', 'green', 'blue'] // -->it should return 'Green wins'
otherwise, it should return 'Draw'
const consecutive = arr => {
for(let i = 0; i < arr.length; i++) {
if(arr[i] === 'green' && arr[i+1] === 'green' && arr[i+2] === 'green' && arr[i+3] === 'green') {
return 'Green Wins'
}
if(arr[i] === 'blue' && arr[i+1] === 'blue' && arr[i+2] === 'blue' && arr[i+3] === 'blue') {
return 'Blue Wins'
}
}
return 'Draw';
}
let greenWins = consecutive(['green', 'blue', 'green', 'green', 'green', 'green', 'blue']);
console.log(greenWins); // --> 'Green Wins'
question from:
https://stackoverflow.com/questions/65884964/returning-elements-consecutively-in-a-row 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…