Skip to content

Instantly share code, notes, and snippets.

@chrisrzhou
Last active November 13, 2016 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisrzhou/74bc5df53a6dde9283b3d1b771ec1f41 to your computer and use it in GitHub Desktop.
Save chrisrzhou/74bc5df53a6dde9283b3d1b771ec1f41 to your computer and use it in GitHub Desktop.
swe_interview_questions

onlyOne

Write a function that returns true or false if exactly one of its parameter is true.

const a = true;
const b = false;
const c = false;
...
onlyOne(a, b, b);  // true
onlyOne(a, b, b, b);  // true
onlyOne(b, b, c, c);  // false
onlyOne(a, b, b, c);  //false
onlyOne(a, a, b);  // false

Solution

const onlyOne() => {
  let sum = 0;
  arguments.forEach((argument) => {
    if (argument) {
      sum += Number(!!argument);
    }
  });
  return sum === 1;
}

Similarly, we can extend implementations for onlyTwo and onlyFive etc by changing the last return check, i.e. sum === n;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment