R
R
R02021-06-22 16:00:59
JavaScript
R0, 2021-06-22 16:00:59

#2 How to replace for with .reduce?

There is this code:

const rX = 'xX';
const rO = 'oO';
let rCountX = 0;
let rCountO = 0;

for (let i = 0; i < str.length; i++) {
  if (rX.includes(str[i])) {
    rCountX++;
  } else if (rO.includes(str[i])) {
    rCountO++;
  }
}
rCountX === rCountO ? true : false;

I want to shorten it by replacing For with .reduce,
but I start to slow down at the moment,
but where should I place rCountX and rCountO in the redux?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WbICHA, 2021-06-22
@R0_none

const rCount = Array.prototype.reduce.call(str, (acc, letter) => {
    if (rX.includes(letter)) {
      acc.X++;
    } else if (rO.includes(letter)) {
      acc.O++;
    }
    return acc;
  }, { X: 0, O: 0 });

But, since this is clearly tic-tac-toe, it can be implemented much more beautifully.
const rCount = Array.prototype.reduce.call(str.toLowerCase(), (acc, letter) => {
    switch(letter) {
      case 'x':
        acc.X++;
        break;
      case 'o':
        acc.O++;
        break;
    }
    return acc;
  }, { X: 0, O: 0 });

P
profesor08, 2021-06-22
@profesor08

https://developer.mozilla.org/en/docs/Web/JavaScri... is a function for working with arrays, while rX, rO are strings. Convert them to arrays and use reduce if you like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question