1

I am trying to count all the times the letter x and the letter o appear in a string and I'm returning true if they appear the same number of times and false otherwise.

I've completed the problem, but when using a ternary statement it forced me to create an extra condition I didn't need since you seem to need 3 operations in a ternary statement so I just counted every time something else appears in a string. Is there any way I can use a ternary statement without creating an unnecessary condition or would I have to use if statements?

function ExOh(str) {
  var ex = 0
  var oh = 0
  var other = 0
  for (var i = 0; i < str.length; i++) {
    str[i] === "x" ? ex++ : str[i] === "o" ? oh++ : other++
  }
  return ex === oh
}

console.log(ExOh("xooabcx$%x73o"));
console.log(ExOh("xooxxo"));
console.log(ExOh("x"));
console.log(ExOh(""));

//wouldn't let me just have one statement after the ternary so I created the other variable.
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
Gwater17
  • 2,018
  • 2
  • 19
  • 38
  • This, is a question that should be on stack code review. First off if your trying to count characters, you can use linq or regex which would be way less code, but if you don't like your ternary use an if. – johnny 5 May 12 '16 at 18:28

1 Answers1

2

Why not add the boolean value?

ex += str[i] === "x";
oh += str[i] === "o";

Example

var a = 0;
a += false;
document.write(a + '<br>');
a += true;
document.write(a + '<br>');

While you just need the difference, you can use a single variable and count up for x and down for o. The return value is the not value of count.

function ExOh(str) {
    var count = 0, i;
    for (i = 0; i < str.length; i++) {
        count += str[i] === "x";
        count -= str[i] === "o";
    }
    return !count;
}

document.write(ExOh("xooabcx$%x73o") + '<br>');
document.write(ExOh("xooxxo") + '<br>');
document.write(ExOh("x") + '<br>');
document.write(ExOh("") + '<br>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392