Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

javascript - Returning elements consecutively in a row

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could take a counter and a value for the last color ach check and exit early if four consecutive same colors/values are in the array.

let array = ['green', 'blue', 'green', 'green', 'green', 'green', 'blue'],
    counter = 0,
    color,
    check = v => {
        if (v === color) return ++counter === 4;
        counter = 1;
        color = v;
    };

if (array.some(check)) console.log(color, 'wins');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...