0

EDIT: So, it seems like there's not really a "better" way of doing this, but a lot of folks are pointing out that a hashmap approach might be more readable/composable.

Given the following function:

const isOpposites = (a, b) => {
  return (
    (a === "SOUTH" && b === "NORTH") ||
    (b === "SOUTH" && a === "NORTH") ||
    (a === "EAST" && b === "WEST") ||
    (a === "WEST" && b === "EAST")
  )
};

Is there a simpler way (one-liner, maybe) of checking whether a and b are opposites?

*There are only four possible values for a and b, they are: "NORTH", "SOUTH","EAST" and "WEST"

4 Answers 4

1

Not a one liner, but probably more readable:

const opposites = {
    "NORTH": "SOUTH",
    "SOUTH": "NORTH",
    "EAST": "WEST",
    "WEST": "EAST"
}

const isOpposites = (a, b) => (opposites[a] === b)
Sign up to request clarification or add additional context in comments.

Comments

1

One option would be to have an object mapping the directions to a number, and have the opposite directions have the same number:

const directions = {
  SOUTH: 1,
  NORTH: 1,
  EAST: 2,
  WEST: 2,
};
const isOpposites = (a, b) => {
  return a !== b && directions[a] === directions[b];
};

1 Comment

Just a note, it doesn't need to be a number, if one needs it might be a good idea to use this dict for something else too, for instance "y" and "x" or or "V" and "H" could be used to determine which axis would be used, other values might also have other meanings.
0

For this specific problem , there are many other ways to solve it but it's the best solution which you have provided. Clearly the space and time complexity is O(n). It's perfect. You don't need any change;

Comments

-1

Could always use modulo:

const CARDINALS = [
  "NORTH",
  "EAST",
  "SOUTH",
  "WEST"
];

function isOpposites(a, b) {
  return CARDINALS.indexOf(a) == (CARDINALS.indexOf(b) + 2) % 4;
}

Of course a simple look-up table like this could also work:

const OPPOSITES = {
  NORTH: 'SOUTH',
  EAST: 'WEST',
  SOUTH: 'NORTH',
  WEST: 'EAST'
};

function isOpposites(a, b) {
  return OPPOSITES[a] === b;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.